use ingraph_codegen::{
interface::{
InterfaceDatabase, InterfaceError, InterfaceField, InterfaceModel, MemberColumn, Operand, Pin,
Tier,
},
model::{AliasOptions, DatabaseKind},
prefix::EmissionPrefix,
union::UnionMember,
};
use quote::ToTokens as _;
use syn::{ext::IdentExt as _, parse::Parser as _};
use crate::{
alias,
attribute::{self, set_once},
errors::Errors,
members::{self, Family},
parse::SORTABLE,
value,
};
#[cfg(test)]
mod member_field_tests;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tower_tests;
const FAMILY: Family = Family {
derive: "#[ingraph::interface]",
noun: "interface",
possessive: "An interface's",
not_an_enum: "an interface IS its member set, one variant per member, and a struct declares no \
alternatives at all",
empty: "an interface is a promise ABOUT its members, so one with none promises nothing of \
anybody; Rust's own law is that an enum with no variants has no value to be",
several: "An interface is a choice BETWEEN member types with one contract over them, so an \
alternative holding two of them is a member nothing promised anything about. Declare \
the pair as a type of its own and carry that",
positional: "A variant's one member is the whole of what it holds, so there is nothing for a \
field name to tell it apart from.",
variant_entry: "a variant takes none. A member is named by the TYPE it carries, and every fact \
about the set is stated once in `fields(…)`",
duplicate: "an interface states its contract over each member ONCE, so a type reached through \
two variants would carry the same promise twice and no fan-out could say which \
variant it answered from",
generic: "an interface's members are the TYPES its variants carry, and a parameter is not one \
until it is substituted; the contract it states over them names the members' own \
columns, which do not exist before that",
};
pub(crate) fn parse(
input: &syn::DeriveInput,
arguments: &[syn::Attribute],
) -> syn::Result<InterfaceModel> {
let mut errors = Errors::default();
crate::host::refuse_a_moved_option_block(&input.attrs, &mut errors);
let options = options(arguments, &mut errors);
members::concrete(&FAMILY, &input.generics, &mut errors);
let members = match members::members(&FAMILY, input, &mut errors) {
Ok(members) => members,
Err(terminal) => return Err(errors.seal(terminal)),
};
members::collisions(&FAMILY, &members, &mut errors);
let fields = fields_model(&input.ident, &members, options.fields, &mut errors);
let model = InterfaceModel {
prefix: EmissionPrefix::default(),
vis: input.vis.clone(),
name: input.ident.clone(),
krate: options
.krate
.unwrap_or_else(|| syn::parse_quote!(::ingraph)),
members,
fields,
error: options.error,
computed_error: options.computed_error,
persist: options.persist,
errors: options.errors,
operand_errors: options.operand_errors,
plural: options.plural.as_ref().map(syn::LitStr::value),
connection: options.connection.as_ref().map(syn::LitStr::value),
edge: options.edge.as_ref().map(syn::LitStr::value),
};
emitted_names(&model, &mut errors);
errors.into_result(model)
}
#[derive(Default)]
struct Options {
krate: Option<syn::Path>,
error: Option<syn::Ident>,
computed_error: Option<syn::Path>,
persist: Vec<InterfaceDatabase>,
errors: Vec<InterfaceError>,
operand_errors: Vec<InterfaceError>,
plural: Option<syn::LitStr>,
connection: Option<syn::LitStr>,
edge: Option<syn::LitStr>,
fields: Option<Vec<Entry>>,
}
struct Entry {
name: syn::Ident,
shape: Shape,
}
enum Shape {
Short(Box<syn::Type>),
Structured(proc_macro2::TokenStream),
}
impl syn::parse::Parse for Entry {
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let name = input.call(syn::Ident::parse_any)?;
if input.peek(syn::Token![:]) {
input.parse::<syn::Token![:]>()?;
return Ok(Self {
name,
shape: Shape::Short(Box::new(input.parse()?)),
});
}
if input.peek(syn::token::Paren) {
let options;
syn::parenthesized!(options in input);
return Ok(Self {
name,
shape: Shape::Structured(options.parse()?),
});
}
Err(syn::Error::new_spanned(&name, FIELD_SHAPE))
}
}
const FIELD_SHAPE: &str = "a field is `<name>: <Type>` or `<name>(type = \"<Type>\", …)` — the short \
form takes every default, and the long one is where a pin, a projection \
or a tier is written";
const NO_FIELDS: &str = "an interface with no fields is a UNION — it states nothing about its \
members, so nothing about it needs a contract, and `#[derive(ingraph::Union)]` \
equips exactly that declaration";
fn options(attrs: &[syn::Attribute], errors: &mut Errors) -> Options {
let mut options = Options::default();
let mut persist_seen = None;
let mut graphql_seen = None;
let mut computed_seen = None;
let mut input_seen = None;
let mut fields_seen = None;
attribute::walk(attrs, errors, |meta, errors| {
if meta.path.is_ident("crate") {
match value::parse_literal::<syn::Path>(
&meta,
"`#[ingraph(crate = \"…\")]` must be a path to the `ingraph` crate, in a string literal",
) {
Ok(path) => set_once(
&mut options.krate,
path,
&meta.path,
"`crate` is declared more than once — one declaration names one crate",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if let Some(walked) = members::refusal_knob(&meta, &mut options.error, errors) {
return walked;
}
if meta.path.is_ident("persist") {
return attribute::block(
&meta,
&mut persist_seen,
"`persist(…)` is declared more than once — one block names the databases",
errors,
|inner, errors| {
interface_database(&inner, &mut options.persist, &mut options.errors, errors)
},
);
}
if meta.path.is_ident("graphql") {
return attribute::block(
&meta,
&mut graphql_seen,
"`graphql(…)` is declared more than once — one block per domain",
errors,
|inner, errors| {
if inner.path.is_ident("computed") {
return attribute::block(
&inner,
&mut computed_seen,
"`computed(…)` is declared more than once in `graphql(…)` — one cell, one type",
errors,
|cell, errors| {
if cell.path.is_ident("error") {
match value::parse_literal::<syn::Path>(&cell, COMPUTED_ERROR) {
Ok(path) => set_once(
&mut options.computed_error,
path,
&cell.path,
"`error` is declared more than once in `graphql(computed(…))` — one cell, \
one type",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
errors.push(misplaced_database(&cell).unwrap_or_else(|| {
attribute::unknown(
&cell,
"unknown entry in `graphql(computed(…))` — it takes `error = \"…\"` and \
nothing else. A computed value is derived from the member rather than read \
out of a row, so the crossing names no database and there is nothing per \
database for a cell to differ about",
&["error"],
)
}));
Ok(())
},
);
}
if inner.path.is_ident("input") {
return attribute::block(
&inner,
&mut input_seen,
"`input(…)` is declared more than once in `graphql(…)` — one block per position",
errors,
|position, errors| operand_position(&position, &mut options.operand_errors, errors),
);
}
if inner.path.is_ident("output") {
errors.push(attribute::unknown(
&inner,
&format!(
"`output(<db>(try_from(error = \"…\")))` types the crossing a member's ROW makes \
onto the wire, and {AN_OUTPUT_FACE_ARRIVES_WITH_THE_ACCESSOR}"
),
&[],
));
return Ok(());
}
if inner.path.is_ident("plural") {
match value::literal(&inner, crate::parse::PLURAL_WORD) {
Ok(word) => {
crate::wire::refuse_invalid_name(&word.value(), &word, errors);
set_once(
&mut options.plural,
word,
&inner.path,
"`plural` is declared more than once in `graphql(…)` — one option, one value",
errors,
);
}
Err(e) => errors.push(e),
}
return Ok(());
}
if inner.path.is_ident("connection") {
return attribute::sdl_name_block(
&inner,
&mut options.connection,
"connection",
errors,
);
}
if inner.path.is_ident("edge") {
return attribute::sdl_name_block(&inner, &mut options.edge, "edge", errors);
}
errors.push(misplaced_database(&inner).unwrap_or_else(|| {
attribute::unknown(
&inner,
"unknown entry in `graphql(…)` at the interface level — it takes \
`computed(error = \"…\")`, `input(comparison(<db>(try_into(error = \"…\"))))`, \
`plural = \"…\"`, and a block per SDL page name (`connection`, `edge`). A field's \
own wire facts are written on the field",
&["computed", "input", "plural", "connection", "edge"],
)
}));
Ok(())
},
);
}
if meta.path.is_ident("fields") {
set_once(
&mut fields_seen,
meta.path.clone(),
&meta.path,
"`fields(…)` is declared more than once — one list carries the whole contract",
errors,
);
match attribute::verbatim(&meta).map(|tokens| {
syn::punctuated::Punctuated::<Entry, syn::Token![,]>::parse_terminated.parse2(tokens)
}) {
Ok(Ok(entries)) => options.fields = Some(entries.into_iter().collect()),
Ok(Err(e)) | Err(e) => {
errors.push(e);
options.fields = Some(Vec::new());
}
}
return Ok(());
}
errors.push(misplaced_database(&meta).unwrap_or_else(|| {
attribute::unknown(
&meta,
"unknown entry in `#[ingraph(…)]` on an interface — it takes `crate = \"…\"`, \
`unwrap_error(rename = \"…\")`, `persist(…)`, `graphql(…)` and `fields(…)`",
&["crate", "unwrap_error", "persist", "graphql", "fields"],
)
}));
Ok(())
});
options
}
const COMPUTED_ERROR: &str = "`error` must be a path to the type a fallible computed field answers \
with, in a string literal";
fn interface_database(
inner: &syn::meta::ParseNestedMeta<'_>,
selected: &mut Vec<InterfaceDatabase>,
cells: &mut Vec<InterfaceError>,
errors: &mut Errors,
) -> syn::Result<()> {
let Some(kind) = database_kind(&inner.path) else {
errors.push(attribute::unknown(
inner,
&format!(
"unknown entry in `persist(…)` on an interface — every entry names a DATABASE, because \
what the block does is select the ones the contract's pins are checked at: {list}",
list = shipped()
),
&DatabaseKind::ALL.map(DatabaseKind::as_str),
));
return Ok(());
};
if selected.iter().any(|database| database.kind == kind) {
errors.push(syn::Error::new_spanned(
&inner.path,
format!(
"`{kind}` is declared more than once in `persist(…)` — one block per database",
kind = kind.as_str()
),
));
attribute::skip_entry(inner);
return Ok(());
}
selected.push(InterfaceDatabase {
kind,
aliases: AliasOptions::default(),
});
let at = selected.len() - 1;
let scope = format!("`{}(…)`", kind.as_str());
let mut leg_seen = None;
let mut alias_seen = None;
attribute::options(inner, |leg| {
if leg.path.is_ident("alias") {
return alias::block(
&leg,
&mut selected[at].aliases,
&mut alias_seen,
&scope,
alias::Depth::Unsized("an interface"),
errors,
);
}
if leg.path.is_ident(ADMITTED_LEG) {
return attribute::block(
&leg,
&mut leg_seen,
"`try_into(…)` is declared more than once for this database — one leg, one type",
errors,
|cell, errors| {
if cell.path.is_ident("error") {
match value::parse_literal::<syn::Path>(&cell, HYDRATION_ERROR) {
Ok(error) => cells.push(InterfaceError { kind, error }),
Err(e) => errors.push(e),
}
return Ok(());
}
errors.push(misplaced_database(&cell).unwrap_or_else(|| {
attribute::unknown(
&cell,
"unknown entry in `persist(<db>(try_into(…)))` — the leg takes `error = \"…\"` and \
nothing else",
&["error"],
)
}));
Ok(())
},
);
}
if let Some(word) = REFUSED_LEGS.iter().find(|word| leg.path.is_ident(word)) {
errors.push(attribute::unknown(
&leg,
&format!(
"`{word}(error = \"…\")` is an interface's per-leg refusal cell, and \
{A_CELL_ARRIVES_WITH_THE_FIND_HALF}"
),
&[],
));
return Ok(());
}
errors.push(attribute::unknown(
&leg,
&format!(
"unknown entry in `persist(<db>(…))` on an interface — a database block here selects the \
database, names the namespace its synthetic words are minted in with `alias(…)`, and \
carries the per-leg cells `{legs}`, each taking `error = \"…\"`; only `{ADMITTED_LEG}` \
is read today",
legs = LEGS.join("`, `")
),
&["alias"].into_iter().chain(LEGS).collect::<Vec<_>>(),
));
Ok(())
})
}
fn operand_position(
position: &syn::meta::ParseNestedMeta<'_>,
cells: &mut Vec<InterfaceError>,
errors: &mut Errors,
) -> syn::Result<()> {
if position.path.is_ident("comparison") {
let mut databases: Vec<DatabaseKind> = Vec::new();
return attribute::options(position, |database| {
operand_database(&database, &mut databases, cells, errors)
});
}
for (word, why) in [
(
"orderby",
"an order input carries a DIRECTION and a subject, never a value — so there is no operand \
here for a crossing to carry and no refusal for a cell to name",
),
(
"pagination",
"a cursor is an opaque engine round trip whose slots already hold the types a database \
stores — nothing about one crosses at the wire",
),
] {
if position.path.is_ident(word) {
errors.push(attribute::unknown(
position,
&format!("`{word}(…)` is not a position `input(…)` admits: {why}"),
&[],
));
return Ok(());
}
}
errors.push(misplaced_database(position).unwrap_or_else(|| {
attribute::unknown(
position,
"unknown entry in `graphql(input(…))` — the position axis admits `comparison(…)` alone, a \
filter's operands being the only wire values that cross into storage",
&["comparison"],
)
}));
Ok(())
}
fn operand_database(
database: &syn::meta::ParseNestedMeta<'_>,
seen: &mut Vec<DatabaseKind>,
cells: &mut Vec<InterfaceError>,
errors: &mut Errors,
) -> syn::Result<()> {
let Some(kind) = database_kind(&database.path) else {
errors.push(attribute::unknown(
database,
&format!(
"unknown entry in `graphql(input(comparison(…)))` — every entry names a DATABASE, a \
predicate being per database: {list}",
list = shipped()
),
&DatabaseKind::ALL.map(DatabaseKind::as_str),
));
return Ok(());
};
if seen.contains(&kind) {
errors.push(syn::Error::new_spanned(
&database.path,
format!(
"`{kind}` is declared more than once in `input(comparison(…))` — one block per database",
kind = kind.as_str()
),
));
attribute::skip_entry(database);
return Ok(());
}
seen.push(kind);
let mut leg_seen = None;
attribute::options(database, |leg| {
if leg.path.is_ident(ADMITTED_LEG) {
return attribute::block(
&leg,
&mut leg_seen,
"`try_into(…)` is declared more than once for this database — one leg, one type",
errors,
|cell, errors| {
if cell.path.is_ident("error") {
match value::parse_literal::<syn::Path>(&cell, OPERAND_ERROR) {
Ok(error) => cells.push(InterfaceError { kind, error }),
Err(e) => errors.push(e),
}
return Ok(());
}
errors.push(misplaced_database(&cell).unwrap_or_else(|| {
attribute::unknown(
&cell,
"unknown entry in `input(comparison(<db>(try_into(…))))` at the interface level — \
the leg takes `error = \"…\"` and nothing else. The CONVERTER is a field's own, \
because which function carries a value is a fact about that column",
&["error"],
)
}));
Ok(())
},
);
}
if let Some(word) = REFUSED_LEGS.iter().find(|word| leg.path.is_ident(word)) {
errors.push(attribute::unknown(
&leg,
&format!(
"`{word}(…)` is not the leg an operand takes — a filter's values LEAVE the wire for the \
types a database stores, which is `{ADMITTED_LEG}`, and an interface performs no \
crossing in the other direction"
),
&[],
));
return Ok(());
}
errors.push(attribute::unknown(
&leg,
&format!(
"unknown entry in `input(comparison(<db>(…)))` at the interface level — the database block \
carries `{ADMITTED_LEG}(error = \"…\")`, which types what crossing a wire filter into this \
database's predicate refuses with"
),
&[ADMITTED_LEG],
));
Ok(())
})
}
const OPERAND_ERROR: &str = "`error` must be a path to the type this database's operand crossing \
answers with, in a string literal";
const AN_OUTPUT_FACE_ARRIVES_WITH_THE_ACCESSOR: &str = "arrives with the interface's own output face — a member's wire object publishes every field under \
its DOMAIN name now, so the fact this waited on is in place and what is left is the face itself; \
until something here reads a member's object there is no crossing for a cell to type";
const HYDRATION_ERROR: &str = "`error` must be a path to the type this database's hydration answers \
with, in a string literal";
const LEGS: [&str; 4] = ["from", "try_from", "into", "try_into"];
const ADMITTED_LEG: &str = "try_into";
const REFUSED_LEGS: [&str; 3] = ["from", "try_from", "into"];
const A_CELL_ARRIVES_WITH_THE_FIND_HALF: &str = "arrives with the find half — what it types is a crossing nothing in this round performs, and an \
entry nobody reads is a rule its author believes they declared";
fn database_kind(path: &syn::Path) -> Option<DatabaseKind> {
DatabaseKind::ALL
.into_iter()
.find(|kind| path.is_ident(kind.as_str()))
}
fn shipped() -> String {
let quoted: Vec<String> = DatabaseKind::ALL
.into_iter()
.map(|kind| format!("`{}`", kind.as_str()))
.collect();
match quoted.split_last() {
Some((last, rest)) => format!("{} and {last}", rest.join(", ")),
None => String::new(),
}
}
fn misplaced_database(inner: &syn::meta::ParseNestedMeta<'_>) -> Option<syn::Error> {
let kind = database_kind(&inner.path)?;
let error = syn::Error::new_spanned(
inner.path.to_token_stream(),
format!(
"`{kind}` is a DATABASE and this is not a database's scope — a database block sits inside a \
DOMAIN, as in `persist({kind}(…))`. The axis is domain, then database, then the cell's own \
entries, and it is the same at every level of this grammar",
kind = kind.as_str()
),
);
attribute::skip_entry(inner);
Some(error)
}
fn fields_model(
interface: &syn::Ident,
members: &[UnionMember],
entries: Option<Vec<Entry>>,
errors: &mut Errors,
) -> Vec<InterfaceField> {
let Some(entries) = entries else {
errors.push(syn::Error::new_spanned(interface, NO_FIELDS));
return Vec::new();
};
if entries.is_empty() {
errors.push(syn::Error::new_spanned(interface, NO_FIELDS));
return Vec::new();
}
let mut fields: Vec<InterfaceField> = Vec::with_capacity(entries.len());
for entry in entries {
if let Some(first) = fields.iter().find(|field| field.name == entry.name) {
errors.push(syn::Error::new_spanned(
&entry.name,
format!(
"`{name}` is declared more than once in `fields(…)` — one field, one promise, and \
`{first}` already carries this name",
name = entry.name,
first = first.name,
),
));
continue;
}
if let Some(field) = field_model(entry, members, errors) {
fields.push(field);
}
}
fields
}
fn field_model(
entry: Entry,
members: &[UnionMember],
errors: &mut Errors,
) -> Option<InterfaceField> {
let name = entry.name;
let tokens = match entry.shape {
Shape::Short(ty) => {
return Some(InterfaceField {
name,
ty: *ty,
tier: Tier::Stored,
marker: None,
copy: false,
pins: Vec::new(),
wire: None,
operands: Vec::new(),
members: Vec::new(),
});
}
Shape::Structured(tokens) => tokens,
};
let mut ty: Option<syn::Type> = None;
let mut type_written = false;
let mut word: Option<crate::parse::Written> = None;
let mut copy = None;
let mut pins: Vec<Pin> = Vec::new();
let mut persist: Option<Written<()>> = None;
let mut computed: Option<Written<Tier>> = None;
let mut wire: Option<syn::Type> = None;
let mut input_seen: Option<syn::Path> = None;
let mut operands: Vec<Operand> = Vec::new();
let mut columns: Vec<MemberColumn> = Vec::new();
let mut renamed_at: Option<syn::Path> = None;
let mut members_seen: Option<syn::Path> = None;
let mut graphql_seen = None;
let mut written = 0_usize;
let walked = syn::meta::parser(|option| {
written += 1;
if option.path.is_ident("type") {
type_written = true;
match value::parse_literal::<syn::Type>(&option, FIELD_TYPE) {
Ok(declared) => set_once(
&mut ty,
declared,
&option.path,
"`type` is declared more than once on a field — one field, one type",
errors,
),
Err(e) => {
errors.push(e);
attribute::skip_entry(&option);
}
}
return Ok(());
}
if option.path.is_ident("copy") {
set_once(
&mut copy,
option.path.clone(),
&option.path,
"`copy` is declared more than once on a field — one claim, one field",
errors,
);
attribute::skip_entry(&option);
return Ok(());
}
if option.path.is_ident("persist") {
let mut seen = persist.as_ref().map(|block| block.at.clone());
let walked = attribute::block(
&option,
&mut seen,
"`persist(…)` is declared more than once on a field — one block per domain",
errors,
|database, errors| field_pin(&name, &database, &mut pins, errors),
);
persist.get_or_insert(Written {
value: (),
at: option.path.clone(),
written,
});
return walked;
}
if option.path.is_ident("graphql") {
return attribute::block(
&option,
&mut graphql_seen,
"`graphql(…)` is declared more than once on a field — one block per domain",
errors,
|inner, errors| {
field_wire(
&inner,
written,
&mut computed,
&mut wire,
&mut input_seen,
&mut operands,
errors,
)
},
);
}
if option.path.is_ident("members") {
set_once(
&mut members_seen,
option.path.clone(),
&option.path,
"`members(…)` is declared more than once on a field — one block carries every member",
errors,
);
if !attribute::has_block(&option) || attribute::empty_group(&option) {
errors.push(syn::Error::new_spanned(&option.path, NO_MEMBERS));
attribute::skip_entry(&option);
return Ok(());
}
renamed_at.get_or_insert(option.path.clone());
return option
.parse_nested_meta(|block| member_column(&name, &block, members, &mut columns, errors));
}
if crate::parse::begins_a_label(&option.path) {
let at = option.path.clone();
if let Some(declared) = crate::parse::label(&option, errors) {
set_once(
&mut word,
declared,
&at,
"an interpretation word is declared more than once on a field — one word, one pin",
errors,
);
}
return Ok(());
}
if let Some(member) = named_member(&option.path, members) {
errors.push(attribute::unknown(
&option,
&format!(
"`{member}` is a MEMBER and this is the field's own scope — a member block lives inside \
`members(…)` now: write `members({member}(field = \"…\"))`. POSITION is what decides a \
key here, so outside that container every key is a word this grammar owns and inside it \
every key is a variant"
),
&[],
));
return Ok(());
}
errors.push(misplaced_database(&option).unwrap_or_else(|| {
attribute::unknown(
&option,
&format!(
"unknown entry on a field of `fields(…)` — it takes `type = \"<Type>\"`, `copy`, \
`persist(…)`, `graphql(…)`, `members(…)`, and {vocabulary}",
vocabulary = crate::parse::label_vocabulary(),
),
&crate::parse::label_words()
.into_iter()
.chain(["type", "copy", "persist", "graphql", "members"])
.collect::<Vec<_>>(),
)
}));
Ok(())
})
.parse2(tokens);
if let Err(e) = walked {
errors.push(e);
}
let tier = tiered(&name, computed, persist, errors);
if let (true, Some(at)) = (tier.computed(), copy.as_ref()) {
errors.push(syn::Error::new_spanned(
at,
format!(
"`{name}` is COMPUTED and claims `copy` — a derivation produces its value rather than \
holding one, so the contract hands it back owned whatever its type is and there is no \
borrow for the claim to displace"
),
));
}
if let (true, Some(at)) = (tier.computed(), renamed_at.as_ref()) {
errors.push(syn::Error::new_spanned(
at,
format!(
"`{name}` is COMPUTED and names a member's column — a value every member derives is read \
out of no column at all, so there is nothing here for a member to call something else. \
Drop the member block, or drop the `computed` word and let the members' rows carry it"
),
));
columns.clear();
}
let Some(ty) = ty else {
if !type_written {
errors.push(syn::Error::new_spanned(&name, FIELD_TYPE));
}
return None;
};
if tier.computed() && !operands.is_empty() {
errors.push(syn::Error::new_spanned(
&name,
format!(
"`{name}` is COMPUTED and names an operand crossing — a value every member derives is a \
column nowhere, so it is statically absent from the filter and no operand of it ever \
enters storage. Drop the `input(comparison(…))` block, or drop the `computed` word and \
let the members' rows carry it"
),
));
operands.clear();
}
let marker = match (tier.computed(), word) {
(true, Some(declared)) => {
errors.push(declared.refuse(format!(
"`{name}` is COMPUTED and names an interpretation word — a value every member derives is a \
column nowhere, so there is no stored reading for a word to pick. Drop the word, or drop \
the `computed` word and let the members' rows carry it"
)));
None
}
(true, None) | (false, None) => None,
(false, Some(declared)) => Some(declared.marker()),
};
Some(InterfaceField {
name,
ty,
tier,
marker,
copy: copy.is_some(),
pins,
wire,
operands,
members: columns,
})
}
fn named_member<'a>(path: &syn::Path, members: &'a [UnionMember]) -> Option<&'a syn::Ident> {
let key = path.get_ident()?;
members
.iter()
.map(|member| &member.ident)
.find(|ident| ident.unraw() == key.unraw())
}
fn member_column(
field: &syn::Ident,
block: &syn::meta::ParseNestedMeta<'_>,
members: &[UnionMember],
columns: &mut Vec<MemberColumn>,
errors: &mut Errors,
) -> syn::Result<()> {
let Some(key) = block.path.get_ident() else {
errors.push(attribute::unknown(block, MEMBER_SHAPE, &[]));
return Ok(());
};
let Some(member) = named_member(&block.path, members) else {
errors.push(syn::Error::new_spanned(
key,
format!(
"`{key}` is not a member variant of this interface — the members are {names}{near}",
names = variants(members),
near = crate::suggest::did_you_mean(
&key.to_string(),
members.iter().map(|member| member.ident.to_string())
),
),
));
attribute::skip_entry(block);
return Ok(());
};
if columns.iter().any(|column| column.variant == *member) {
errors.push(syn::Error::new_spanned(
key,
format!(
"`{key}` is declared more than once on `{field}` — one member, one column, and a variant \
that carried this field under two names would carry it under neither"
),
));
attribute::skip_entry(block);
return Ok(());
}
let variant = member.clone();
let mut column: Option<syn::Ident> = None;
let walked = attribute::options(block, |entry| {
if entry.path.is_ident("field") {
match value::literal(&entry, MEMBER_FIELD)
.and_then(|literal| value::named_field(&literal, MEMBER_FIELD))
{
Ok(named) => set_once(
&mut column,
named,
&entry.path,
"`field` is declared more than once in a member block — one member, one column",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
errors.push(attribute::unknown(
&entry,
"unknown entry in a member block — it takes `field = \"…\"` and nothing else. What a member \
may differ about is the COLUMN it carries the field under; its type is the contract's, and \
its pins are the interface's",
&["field"],
));
Ok(())
});
match column {
Some(column) => columns.push(MemberColumn { variant, column }),
None => errors.push(syn::Error::new_spanned(key, MEMBER_SHAPE)),
}
walked
}
const MEMBER_SHAPE: &str = "a member block is `<Variant>(field = \"…\")`, inside `members(…)` — \
naming the column that member carries the field under is the only thing \
it is for";
const NO_MEMBERS: &str = "`members(…)` names no member — the block is where a member says it \
carries this field under another name, so one with nothing in it says \
nothing. Omit it, and every member carries the field under the \
interface's own name";
const MEMBER_FIELD: &str = "`field` must be the column this member carries the field under, as an identifier in a string \
literal";
fn variants(members: &[UnionMember]) -> String {
let quoted: Vec<String> = members
.iter()
.map(|member| format!("`{}`", member.ident))
.collect();
match quoted.split_last() {
Some((last, [])) => last.clone(),
Some((last, rest)) => format!("{} and {last}", rest.join(", ")),
None => String::new(),
}
}
const FIELD_TYPE: &str = "a field names its type — `<name>: <Type>` in the short form, `type = \
\"<Type>\"` in the long one, in a string literal as every other `type` \
in this grammar is written";
struct Written<T> {
value: T,
at: syn::Path,
written: usize,
}
fn tiered(
name: &syn::Ident,
computed: Option<Written<Tier>>,
persist: Option<Written<()>>,
errors: &mut Errors,
) -> Tier {
let Some(computed) = computed else {
return Tier::Stored;
};
let Some(persist) = persist else {
return computed.value;
};
if computed.written < persist.written {
errors.push(syn::Error::new_spanned(
&persist.at,
format!(
"`{name}` is COMPUTED and pinned — a value a member derives is not a column its row holds, \
so there is nothing here for a database to store it as. Drop the pin, or drop the \
`computed` word and let the members' rows carry it"
),
));
} else {
errors.push(syn::Error::new_spanned(
&computed.at,
format!(
"`{name}` is PINNED and computed — a column the members' rows hold is not a value they \
derive, so there is nothing here for a derivation to answer. Drop the word, or drop the \
`persist(…)` block and let every member derive it"
),
));
}
computed.value
}
fn field_pin(
field: &syn::Ident,
database: &syn::meta::ParseNestedMeta<'_>,
pins: &mut Vec<Pin>,
errors: &mut Errors,
) -> syn::Result<()> {
let Some(kind) = database_kind(&database.path) else {
if database.path.is_ident(SORTABLE) {
errors.push(attribute::named(
database,
SORTABLE_IS_A_RECORDS_WORD.to_owned(),
));
return Ok(());
}
errors.push(attribute::unknown(
database,
&format!(
"unknown entry in `persist(…)` on a field — every entry names a DATABASE, because a stored \
type is one database's: {list}",
list = shipped()
),
&DatabaseKind::ALL.map(DatabaseKind::as_str),
));
return Ok(());
};
if pins.iter().any(|pin| pin.kind == kind) {
errors.push(syn::Error::new_spanned(
&database.path,
format!(
"`{kind}` is declared more than once in `{field}`'s `persist(…)` — one block per database",
kind = kind.as_str()
),
));
attribute::skip_entry(database);
return Ok(());
}
let mut stored: Option<syn::Type> = None;
let walked = attribute::options(database, |cell| {
if cell.path.is_ident("type") {
match value::parse_literal::<syn::Type>(&cell, PIN_TYPE) {
Ok(declared) => set_once(
&mut stored,
declared,
&cell.path,
"`type` is declared more than once in a database's block — one column, one stored type",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
errors.push(attribute::unknown(
&cell,
"unknown entry in `persist(<db>(…))` on a field — it takes `type = \"…\"`, the type this \
database keeps the column at. A field with no entry here is stored at the type it was \
declared with",
&["type"],
));
Ok(())
});
pins.push(Pin { kind, stored });
walked
}
const PIN_TYPE: &str = "`type` must be the type this database stores the column at, in a string \
literal";
const SORTABLE_IS_A_RECORDS_WORD: &str = "`sortable` is a RECORD's word — an interface pin promises \
a shared reading across every arm, and projecting an \
arm's companion column through the union is a widening \
this framework has not built. The pin's collection terms \
are the degrade law's, as they were.";
fn field_wire(
inner: &syn::meta::ParseNestedMeta<'_>,
written: usize,
computed: &mut Option<Written<Tier>>,
wire: &mut Option<syn::Type>,
input: &mut Option<syn::Path>,
operands: &mut Vec<Operand>,
errors: &mut Errors,
) -> syn::Result<()> {
for (word, tier) in [
("computed", Tier::Computed),
("try_computed", Tier::TryComputed),
] {
if inner.path.is_ident(word) {
set_once(
computed,
Written {
value: tier,
at: inner.path.clone(),
written,
},
&inner.path,
"a field is COMPUTED once — `computed` and `try_computed` are the same claim about whether \
deriving it can fail, and there is no third answer",
errors,
);
attribute::skip_entry(inner);
return Ok(());
}
}
if inner.path.is_ident("type") {
match value::parse_literal::<syn::Type>(inner, WIRE_TYPE) {
Ok(declared) => set_once(
wire,
declared,
&inner.path,
"`type` is declared more than once in `graphql(…)` — one field, one wire form",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if inner.path.is_ident("input") {
return attribute::block(
inner,
input,
"`input(…)` is declared more than once on a field — one block per position",
errors,
|position, errors| field_operand_position(&position, operands, errors),
);
}
if inner.path.is_ident("output") {
errors.push(attribute::unknown(
inner,
&format!(
"`output(<db>(from = \"…\"))` is a field's own row-to-wire crossing, and \
{AN_OUTPUT_FACE_ARRIVES_WITH_THE_ACCESSOR}"
),
&[],
));
return Ok(());
}
errors.push(misplaced_database(inner).unwrap_or_else(|| {
attribute::unknown(
inner,
"unknown entry in `graphql(…)` on a field — it takes `type = \"…\"`, \
`input(comparison(<db>(try_into = \"…\")))`, and one of `computed` or `try_computed`",
&["type", "input", "computed", "try_computed"],
)
}));
Ok(())
}
fn field_operand_position(
position: &syn::meta::ParseNestedMeta<'_>,
operands: &mut Vec<Operand>,
errors: &mut Errors,
) -> syn::Result<()> {
if position.path.is_ident("comparison") {
return attribute::options(position, |database| {
field_operand(&database, operands, errors)
});
}
errors.push(misplaced_database(position).unwrap_or_else(|| {
attribute::unknown(
position,
"unknown entry in `graphql(input(…))` on a field — the position axis admits `comparison(…)` \
alone, a filter's operands being the only wire values that cross into storage",
&["comparison"],
)
}));
Ok(())
}
fn field_operand(
database: &syn::meta::ParseNestedMeta<'_>,
operands: &mut Vec<Operand>,
errors: &mut Errors,
) -> syn::Result<()> {
let Some(kind) = database_kind(&database.path) else {
errors.push(attribute::unknown(
database,
&format!(
"unknown entry in `graphql(input(comparison(…)))` on a field — every entry names a \
DATABASE, an operand crossing into one being per database: {list}",
list = shipped()
),
&DatabaseKind::ALL.map(DatabaseKind::as_str),
));
return Ok(());
};
if operands.iter().any(|operand| operand.kind == kind) {
errors.push(syn::Error::new_spanned(
&database.path,
format!(
"`{kind}` is declared more than once for this field's operand — one database, one crossing",
kind = kind.as_str()
),
));
attribute::skip_entry(database);
return Ok(());
}
let mut seen = None;
attribute::options(database, |leg| {
if leg.path.is_ident(ADMITTED_LEG) {
set_once(
&mut seen,
leg.path.clone(),
&leg.path,
"`try_into` is declared more than once for this database — one leg, one function",
errors,
);
match value::parse_literal::<syn::Path>(&leg, OPERAND_CONVERT) {
Ok(convert) => operands.push(Operand { kind, convert }),
Err(e) => errors.push(e),
}
return Ok(());
}
if let Some(word) = REFUSED_LEGS.iter().find(|word| leg.path.is_ident(word)) {
errors.push(attribute::unknown(
&leg,
&format!(
"`{word} = \"…\"` is not the leg an operand takes — a filter's values LEAVE the wire for \
the types a database stores, which is `{ADMITTED_LEG}`"
),
&[],
));
return Ok(());
}
errors.push(attribute::unknown(
&leg,
&format!(
"unknown entry in `input(comparison(<db>(…)))` on a field — the database block takes \
`{ADMITTED_LEG} = \"…\"`, the function this field's operands enter storage through"
),
&[ADMITTED_LEG],
));
Ok(())
})
}
const OPERAND_CONVERT: &str = "`try_into` must be a path to the function this field's operands \
enter storage through, in a string literal";
const WIRE_TYPE: &str = "`type` must be the form this field takes on the wire, in a string literal";
fn emitted_names(model: &InterfaceModel, errors: &mut Errors) {
let mut seen: Vec<(syn::Ident, String)> =
vec![(model.name.clone(), "the interface's own name".to_owned())];
for declared in model.emitted_types() {
if let Some((_, held)) = seen.iter().find(|(already, _)| *already == declared.name) {
let at = model
.error
.as_ref()
.map_or_else(|| model.name.span(), syn::Ident::span);
errors.push(syn::Error::new(
at,
format!(
"`{name}` would be {role}, and it is already {held} — an interface lands its refusal, its \
two contract traits and its own projection in the declaring scope, so each needs a name \
of its own",
name = declared.name,
role = declared.role,
),
));
continue;
}
seen.push((declared.name, declared.role.to_string()));
}
}