use ingraph_codegen::construct::{Blanket, Build, Construction, Cross, Injection, Seat};
use quote::ToTokens as _;
use crate::{attribute, errors::Errors, value};
pub(crate) const WORD: &str = "builder";
const CONTAINER: [&str; 5] = ["entry", "finish", "fallible", "on", "call"];
const FIELD: [&str; 8] = [
"arg",
"finish_arg",
"with",
"set",
"into",
"map",
"option",
"skip",
];
const SEATS: [&str; 4] = ["arg", "finish_arg", "with", "set"];
const METHOD: &str = "must name a METHOD, as a plain identifier in a string literal";
pub(crate) fn container(
meta: &syn::meta::ParseNestedMeta<'_>,
slot: &mut Option<Construction>,
errors: &mut Errors,
) -> syn::Result<()> {
let mut declared = Construction {
at: Some(meta.path.clone()),
..Construction::default()
};
let mut entry_at: Option<syn::Path> = None;
let mut finish_at: Option<syn::Path> = None;
let mut fallible_at: Option<syn::Path> = None;
let walked = attribute::options(meta, |inner| {
if inner.path.is_ident("entry") {
match value::parse_literal::<syn::Ident>(&inner, &format!("`entry = \"…\"` {METHOD}")) {
Ok(name) => {
if entry_at.is_none() {
declared.entry = name;
}
attribute::set_once(
&mut entry_at,
inner.path.clone(),
&inner.path,
"`entry` is declared more than once — one protocol opens with one call",
errors,
);
}
Err(e) => errors.push(e),
}
return Ok(());
}
if inner.path.is_ident("finish") {
match value::parse_literal::<syn::Ident>(&inner, &format!("`finish = \"…\"` {METHOD}")) {
Ok(name) => {
if finish_at.is_none() {
declared.finish = Some(name);
}
attribute::set_once(
&mut finish_at,
inner.path.clone(),
&inner.path,
"`finish` is declared more than once — one protocol closes with one call",
errors,
);
}
Err(e) => errors.push(e),
}
return Ok(());
}
if inner.path.is_ident("fallible") {
attribute::skip_entry(&inner);
attribute::set_once(
&mut fallible_at,
inner.path.clone(),
&inner.path,
"`fallible` is declared more than once — one word, one protocol",
errors,
);
declared.fallible = true;
return Ok(());
}
if inner.path.is_ident("on") {
match blanket(&inner) {
Ok(rule) => declared.blanket.push(rule),
Err(e) => errors.push(e),
}
return Ok(());
}
if inner.path.is_ident("call") {
match injection(&inner, errors) {
Ok(call) => declared.calls.push(call),
Err(e) => errors.push(e),
}
return Ok(());
}
errors.push(attribute::unknown(
&inner,
"unknown entry in `builder(…)` on a declaration — it takes `entry = \"…\"`, \
`finish = \"…\"`, `fallible`, `on(<Type>, into)` and `call(with = \"…\", value = \"…\")`. \
The per-column words — `arg`, `with`, `set`, `map` and the rest — are written in a \
`builder(…)` on the FIELD they are about",
&CONTAINER,
));
Ok(())
});
attribute::set_once(
slot,
declared,
&meta.path,
"`builder` is declared more than once — one declaration describes one protocol",
errors,
);
walked
}
pub(crate) fn field(
meta: &syn::meta::ParseNestedMeta<'_>,
slot: &mut Option<Build>,
errors: &mut Errors,
) -> syn::Result<()> {
let mut declared = Build {
at: Some(meta.path.clone()),
..Build::default()
};
let mut seats: Vec<(&'static str, syn::Path)> = Vec::new();
let mut cross_at: Option<syn::Path> = None;
let mut option_at: Option<syn::Path> = None;
let mut skip_at: Option<syn::Path> = None;
let walked = attribute::options(meta, |inner| {
if let Some(word) = SEATS.into_iter().find(|word| inner.path.is_ident(word)) {
match seat(&inner, word) {
Ok(taken) => {
if seats.is_empty() {
declared.seat = Some(taken);
}
seats.push((word, inner.path.clone()));
}
Err(e) => errors.push(e),
}
return Ok(());
}
if inner.path.is_ident("into") {
attribute::skip_entry(&inner);
set_cross(
&mut declared,
&mut cross_at,
Cross::Into,
&inner.path,
errors,
);
return Ok(());
}
if inner.path.is_ident("map") {
match value::parse_literal::<syn::Path>(
&inner,
"`map = \"…\"` names the FUNCTION this column's value crosses through — a `fn(T) -> U`, as \
a path in a string literal",
) {
Ok(path) => set_cross(
&mut declared,
&mut cross_at,
Cross::Map(path),
&inner.path,
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if inner.path.is_ident("option") {
attribute::skip_entry(&inner);
attribute::set_once(
&mut option_at,
inner.path.clone(),
&inner.path,
"`option` is declared more than once on this field — one word, one column",
errors,
);
declared.option = true;
return Ok(());
}
if inner.path.is_ident("skip") {
attribute::skip_entry(&inner);
attribute::set_once(
&mut skip_at,
inner.path.clone(),
&inner.path,
"`skip` is declared more than once in `builder(…)` on this field — one word, one column",
errors,
);
declared.skip = true;
return Ok(());
}
errors.push(attribute::unknown(
&inner,
"unknown entry in `builder(…)` on a field — it takes one SEAT word (`arg`, `finish_arg`, \
`with[ = \"…\"]`, `set[ = \"…\"]`), one CROSSING word (`into`, `map = \"…\"`), and the two \
that stand on their own: `option` and `skip`. `entry`, `finish`, `fallible`, `on` and \
`call` are facts about the whole protocol and are written on the DECLARATION",
&FIELD,
));
Ok(())
});
refuse_two_seats(&seats, errors);
refuse_a_skipped_seat(skip_at.as_ref(), &seats, errors);
refuse_a_pinned_option(option_at.as_ref(), cross_at.as_ref(), &declared, errors);
attribute::set_once(
slot,
declared,
&meta.path,
"`builder` is declared more than once on this field — one column fills one seat",
errors,
);
walked
}
fn seat(meta: &syn::meta::ParseNestedMeta<'_>, word: &'static str) -> syn::Result<Seat> {
match word {
"arg" | "finish_arg" => {
if attribute::has_value(meta) || attribute::has_block(meta) {
return Err(attribute::named(
meta,
format!(
"`{word}` names a POSITION in an argument list, not a method — there is nothing here \
to rename. The words that take a name are `with = \"…\"` and `set = \"…\"`"
),
));
}
attribute::skip_entry(meta);
Ok(if word == "arg" {
Seat::Arg
} else {
Seat::FinishArg
})
}
_ => {
if !attribute::has_value(meta) {
attribute::skip_entry(meta);
return Ok(if word == "with" {
Seat::With(None)
} else {
Seat::Set(None)
});
}
let name = value::parse_literal::<syn::Ident>(meta, &format!("`{word} = \"…\"` {METHOD}"))?;
Ok(if word == "with" {
Seat::With(Some(name))
} else {
Seat::Set(Some(name))
})
}
}
}
fn set_cross(
declared: &mut Build,
at: &mut Option<syn::Path>,
cross: Cross,
path: &syn::Path,
errors: &mut Errors,
) {
if at.is_none() {
declared.cross = Some(cross);
}
attribute::set_once(
at,
path.clone(),
path,
"a column crosses ONE way — `into` pins the bridge's target and `map = \"…\"` replaces the \
bridge with a function of your own, and a field that wrote both has said two things about one \
argument",
errors,
);
}
fn blanket(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<Blanket> {
const SHAPE: &str = "`on(…)` states a crossing for every column of ONE TYPE, and is written \
`on(<Type>, into)` — the type first, then the word";
if !attribute::has_block(meta) {
return Err(attribute::named(meta, SHAPE.to_owned()));
}
let tokens = attribute::verbatim(meta)?;
let at = tokens.clone();
let rule = syn::parse2::<Rule>(tokens).map_err(|_| syn::Error::new_spanned(&at, SHAPE))?;
if rule.words.len() != 1 || rule.words[0] != "into" {
return Err(syn::Error::new_spanned(
&at,
format!(
"{SHAPE}. `into` is the only crossing a blanket states today: it says every column of the \
type reaches a seat spelled `impl Into<…>`, which is the one fact a per-type rule can \
carry — a `map` function is per column and belongs on the column"
),
));
}
Ok(Blanket { ty: rule.ty })
}
struct Rule {
ty: syn::Type,
words: Vec<syn::Ident>,
}
impl syn::parse::Parse for Rule {
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let ty = input.parse::<syn::Type>()?;
let mut words = Vec::new();
while input.parse::<Option<syn::Token![,]>>()?.is_some() {
if input.is_empty() {
break;
}
words.push(input.parse::<syn::Ident>()?);
}
if input.is_empty() {
return Ok(Self { ty, words });
}
Err(input.error("a trailing token"))
}
}
fn injection(meta: &syn::meta::ParseNestedMeta<'_>, errors: &mut Errors) -> syn::Result<Injection> {
const SHAPE: &str = "a `call` names the method and what to hand it, and is written \
`call(with = \"with_thing\", value = \"<expr>\")`";
let mut method: Option<syn::Ident> = None;
let mut supplied: Option<syn::Expr> = None;
if !attribute::has_block(meta) || attribute::empty_group(meta) {
return Err(attribute::named(
meta,
format!("`call(…)` is a link this declaration supplies rather than a column — {SHAPE}"),
));
}
meta.parse_nested_meta(|inner| {
if inner.path.is_ident("with") {
match value::parse_literal::<syn::Ident>(&inner, &format!("`with = \"…\"` {METHOD}")) {
Ok(name) => attribute::set_once(
&mut method,
name,
&inner.path,
"`with` is declared more than once in `call(…)` — one entry, one method",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
if inner.path.is_ident("value") {
match value::parse_literal::<syn::Expr>(
&inner,
"`value = \"…\"` is the EXPRESSION this link is handed, in a string literal — a literal, a \
path, a call, whatever the upstream's argument really is",
) {
Ok(expr) => attribute::set_once(
&mut supplied,
expr,
&inner.path,
"`value` is declared more than once in `call(…)` — one link carries one argument",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
errors.push(attribute::unknown(
&inner,
&format!("unknown entry in `call(…)` — {SHAPE}"),
&["with", "value"],
));
Ok(())
})?;
match (method, supplied) {
(Some(method), Some(value)) => Ok(Injection { method, value }),
(Some(_), None) => Err(syn::Error::new_spanned(
&meta.path,
format!(
"`call(…)` names a method and hands it nothing — a link with no argument is a call this \
emission has no way to write: {SHAPE}"
),
)),
(None, _) => Err(syn::Error::new_spanned(
&meta.path,
format!("`call(…)` supplies a value and names no method to hand it to: {SHAPE}"),
)),
}
}
fn refuse_two_seats(seats: &[(&'static str, syn::Path)], errors: &mut Errors) {
let [(first, _), (second, at), ..] = seats else {
return;
};
errors.push(syn::Error::new_spanned(
at,
format!(
"`{first}` and `{second}` are both declared on this field, and each names a DIFFERENT place \
in the protocol — a column's value is handed over once. `arg` and `finish_arg` are \
positions in the two argument lists; `with` is a link that consumes and returns the value \
and `set` is one that mutates it in place"
),
));
}
fn refuse_a_skipped_seat(
skip: Option<&syn::Path>,
seats: &[(&'static str, syn::Path)],
errors: &mut Errors,
) {
let (Some(skip), Some((word, _))) = (skip, seats.first()) else {
return;
};
errors.push(syn::Error::new_spanned(
skip,
format!(
"`skip` says this column is NOT handed back to the construction at all, and `{word}` says \
which call it is handed to — one of them is not true. Delete whichever states the wrong \
thing; a skipped column is filled by whatever the wrapped type's own constructor puts \
there, which is a round trip only its author can vouch for"
),
));
}
fn refuse_a_pinned_option(
option: Option<&syn::Path>,
cross: Option<&syn::Path>,
declared: &Build,
errors: &mut Errors,
) {
let (Some(option), Some(_), Some(Cross::Into)) = (option, cross, declared.cross.as_ref()) else {
return;
};
errors.push(syn::Error::new_spanned(
option,
"`into` pins the crossing's target to the type this field restates, and `option` says the \
crossing happens INSIDE the option rather than over it — so together they pin the option \
where the item is what crosses. Where the seat really is `impl Into<Option<…>>`, `into` \
alone says so; where it takes the option and the ITEM has to cross, `option` alone does",
));
}
pub(crate) fn refuse_without_a_remote(
remote: Option<&syn::Path>,
construction: Option<&syn::Path>,
fields: impl Iterator<Item = syn::Path>,
noun: &str,
errors: &mut Errors,
) {
if remote.is_some() {
return;
}
for at in construction.cloned().into_iter().chain(fields) {
errors.push(syn::Error::new_spanned(
at,
format!(
"`{WORD}(…)` describes how a type SOMEBODY ELSE declared is built, and this {noun} is its \
own fields — a raise writes the struct literal, and there is no call sequence for these \
words to describe. They belong on a declaration carrying `remote = \"…\"`"
),
));
}
}
pub(crate) fn refuse_a_homeless_argument(
construction: &Construction,
fields: &[(syn::Ident, Build)],
errors: &mut Errors,
) {
if construction.finish.is_some() {
return;
}
for (name, build) in fields {
if !matches!(build.seat, Some(Seat::FinishArg)) {
continue;
}
let at = build
.at
.as_ref()
.map_or_else(|| name.to_token_stream(), quote::ToTokens::to_token_stream);
errors.push(syn::Error::new_spanned(
at,
format!(
"`finish_arg` puts `{name}` in the argument list of the protocol's CLOSING call, and this \
declaration has no closing call — without `builder(finish = \"…\")` the entry hands back \
the value itself and there is one argument list. Write the `finish`, or make this an \
`arg`"
),
));
}
}
pub(crate) fn refuse_a_whole_non_option(
optional: bool,
build: Option<&Build>,
errors: &mut Errors,
) {
let Some(build) = build else { return };
if optional || !build.option {
return;
}
let at = build.at.as_ref().expect("a parsed block keeps its word");
errors.push(syn::Error::new_spanned(
at,
"`option` says the seat takes this column's `Option` WHOLE — crossing the item rather than the \
option — and this column has no empty state to take. `optional` is what declares one, and it \
is read rather than the field's spelled type: a macro holds tokens, and a type alias hiding an \
`Option` is exactly why a spelling is not trusted here",
));
}
#[cfg(test)]
mod tests;