use std::collections::BTreeMap;
use ingraph_codegen::flags::{BitWidth, FlagBit, FlagsModel};
use crate::{
attribute::{self, set_once},
r#enum::listed,
errors::Errors,
value, wire,
};
#[cfg(test)]
mod tests;
const WORD: &str = "#[ingraph::flags(…)]";
const CRATE_PATH: &str =
"`#[ingraph::flags(crate = \"…\")]` must be a path to the `ingraph` crate, in a string literal";
const CRATE_ONCE: &str = "`crate` is declared more than once — one declaration names one crate";
const REMOTE_PATH: &str = "`#[ingraph::flags(…, remote = \"…\")]` must be a path to the flags set \
this one mirrors, in a string literal";
const REMOTE_ONCE: &str =
"`remote` is declared more than once — one declaration mirrors one flags set";
pub(crate) fn parse(
input: &syn::DeriveInput,
options: &[syn::Attribute],
) -> syn::Result<FlagsModel> {
let mut errors = Errors::default();
let Options {
krate,
width,
named,
remote,
wire_name,
} = self::options(options, &mut errors);
let mode = if remote.is_some() {
Mode::Mirror
} else {
Mode::Declared
};
moved_option_block(&input.attrs, &mut errors);
concrete(&input.generics, &mut errors);
match wire_name.as_ref() {
Some(word) => wire::refuse_invalid_name(&word.value(), word, &mut errors),
None => wire::refuse_invalid_name(
&syn::ext::IdentExt::unraw(&input.ident).to_string(),
&input.ident,
&mut errors,
),
}
let Some(width) = width else {
if !named {
errors.push(syn::Error::new_spanned(
&input.ident,
format!(
"`{WORD}` names its WIDTH — the integer a column of this type is stored as, and the \
number of bits a declaration may number. Write `#[ingraph::flags(u32)]`, or any of {}",
listed(&BitWidth::ALL.map(BitWidth::as_str))
),
));
}
return Err(
errors
.into_result(())
.expect_err("a declaration with no usable width has always recorded why"),
);
};
let bits = match self::bits(input, width, mode, &mut errors) {
Ok(bits) => bits,
Err(terminal) => return Err(errors.seal(terminal)),
};
collisions(&bits, &mut errors);
errors.into_result(FlagsModel {
krate: krate.unwrap_or_else(|| syn::parse_quote!(::ingraph)),
vis: input.vis.clone(),
name: input.ident.clone(),
width,
bits,
attrs: forwarded(&input.attrs),
remote,
wire_name: wire_name.map(|word| word.value()),
})
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Mode {
Declared,
Mirror,
}
struct Options {
krate: Option<syn::Path>,
width: Option<BitWidth>,
named: bool,
remote: Option<syn::Path>,
wire_name: Option<syn::LitStr>,
}
fn options(attrs: &[syn::Attribute], errors: &mut Errors) -> Options {
let mut krate = None;
let mut width = None;
let mut named = false;
let mut remote = None;
let mut wire_name = None;
attribute::walk(attrs, errors, |meta, errors| {
if meta.path.is_ident("crate") {
match value::parse_literal::<syn::Path>(&meta, CRATE_PATH) {
Ok(path) => set_once(&mut krate, path, &meta.path, CRATE_ONCE, errors),
Err(e) => errors.push(e),
}
return Ok(());
}
if meta.path.is_ident("remote") {
match value::parse_literal::<syn::Path>(&meta, REMOTE_PATH) {
Ok(path) => set_once(&mut remote, path, &meta.path, REMOTE_ONCE, errors),
Err(e) => errors.push(e),
}
return Ok(());
}
if meta.path.is_ident("graphql") {
return attribute::named_block(
&meta,
&mut wire_name,
"graphql",
"schema type",
errors,
|option| value::literal(option, attribute::SDL_NAME),
);
}
if let Some(word) = meta.path.get_ident().map(ToString::to_string) {
if let Some(carried) = BitWidth::named(&word) {
named = true;
set_once(
&mut width,
carried,
&meta.path,
"the width is declared more than once — one column has one width",
errors,
);
return Ok(());
}
if UNCARRIED.contains(&word.as_str()) {
named = true;
errors.push(syn::Error::new_spanned(
&meta.path,
format!(
"`{word}` is not a width a flags set can be stored at — the framework's carrier table \
covers {}, and no wider: MySQL alone has a native `u64` and no dialect carries a \
128-bit integer. The SIGNED widths are absent for a different reason — a flag is a \
BIT, and `iN`'s top bit is negative, so it is one bit no declaration could write",
listed(&BitWidth::ALL.map(BitWidth::as_str))
),
));
return Ok(());
}
}
errors.push(attribute::unknown(
&meta,
&format!(
"unknown entry in `{WORD}` — a flags declaration takes its WIDTH ({}), plus \
`graphql(rename = \"…\")`, `remote = \"…\"` and `crate = \"…\"`",
listed(&BitWidth::ALL.map(BitWidth::as_str))
),
&["crate", "remote", "graphql"]
.into_iter()
.chain(BitWidth::ALL.map(BitWidth::as_str))
.collect::<Vec<_>>(),
));
Ok(())
});
Options {
krate,
width,
named,
remote,
wire_name,
}
}
const UNCARRIED: [&str; 9] = [
"u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize",
];
fn concrete(generics: &syn::Generics, errors: &mut Errors) {
const WHY: &str = "generic flags sets are not supported — the expansion is one `bitflags!` type \
with one bit table, and a parameter has no type until it is substituted";
if !generics.params.is_empty() {
errors.push(syn::Error::new_spanned(generics, WHY));
} else if let Some(clause) = &generics.where_clause {
errors.push(syn::Error::new_spanned(clause, WHY));
}
}
fn bits(
input: &syn::DeriveInput,
width: BitWidth,
mode: Mode,
errors: &mut Errors,
) -> syn::Result<Vec<FlagBit>> {
let syn::Data::Enum(data) = &input.data else {
return Err(syn::Error::new_spanned(
&input.ident,
format!(
"`{WORD}` supports enums only — the manifest is a set of NAMES with VALUES, which is what \
an enum spells and what a struct body cannot hold. The expansion is a `bitflags!` struct \
either way; the enum is what the author writes, not what they get"
),
));
};
if data.variants.is_empty() {
return Err(syn::Error::new_spanned(
&input.ident,
format!(
"an enum with no variants declares no flags — there is no bit to store, no field for a \
client to ask for, and the emitted filter would guard a column whose every value is \
empty. `{WORD}` has nothing to emit for one"
),
));
}
let mut parsed = Vec::with_capacity(data.variants.len());
for variant in &data.variants {
if !matches!(variant.fields, syn::Fields::Unit) {
errors.push(syn::Error::new_spanned(
&variant.ident,
format!(
"`{WORD}` takes UNIT variants only — `{}` carries data. A bit is a NAME and a NUMBER; \
there is no payload a stored bit could hold",
variant.ident
),
));
continue;
}
let Some(value) = self::value(variant, width, errors) else {
continue;
};
let mut bit = FlagBit {
ident: variant.ident.clone(),
rename: None,
upstream: None,
value,
attrs: forwarded(&variant.attrs),
};
rename(variant, &mut bit, mode, errors);
parsed.push(bit);
}
Ok(parsed)
}
fn value(variant: &syn::Variant, width: BitWidth, errors: &mut Errors) -> Option<u128> {
let Some((_, expression)) = &variant.discriminant else {
errors.push(syn::Error::new_spanned(
&variant.ident,
format!(
"`{}` names no bit — a flags declaration writes every value EXPLICITLY. An implicit \
numbering would come from a bit's POSITION, so reordering the declaration would rewrite \
every stored row, silently. Write `{} = <bit>` and give it the number it already has in \
your data",
variant.ident, variant.ident
),
));
return None;
};
let Some(value) = literal(expression) else {
errors.push(syn::Error::new_spanned(
expression,
"a bit's value is an integer LITERAL or a shift of one — `0x4`, `0b100`, `4` or `1 << 2`. \
This door has to prove the value is a single bit inside the declared width, and an \
expression it cannot evaluate is one it cannot prove anything about",
));
return None;
};
if value == 0 {
errors.push(syn::Error::new_spanned(
expression,
format!(
"`{}` is `0`, which sets no bit — a value with no bit is not a flag, it is the EMPTY set, \
and every flags type already has one of those",
variant.ident
),
));
return None;
}
if value > width.ceiling() {
errors.push(syn::Error::new_spanned(
expression,
format!(
"`{value:#x}` does not fit `{}` — this declaration numbers {} bits, so the highest one is \
`{:#x}`",
width.as_str(),
width.count(),
1u128 << (width.count() - 1)
),
));
return None;
}
if value.count_ones() > 1 {
errors.push(syn::Error::new_spanned(
expression,
format!(
"`{value:#x}` sets {} bits — a declared flag is ONE bit. A composite mask has no per-flag \
boolean a client could ask for and no single answer to *is it set*; write the bits it \
combines and let a caller ask for them together",
value.count_ones()
),
));
return None;
}
Some(value)
}
fn literal(expression: &syn::Expr) -> Option<u128> {
match expression {
syn::Expr::Paren(inner) => literal(&inner.expr),
syn::Expr::Group(inner) => literal(&inner.expr),
syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Int(int),
..
}) => int.base10_parse::<u128>().ok(),
syn::Expr::Binary(syn::ExprBinary {
left,
op: syn::BinOp::Shl(_),
right,
..
}) => {
let base = literal(left)?;
let shift = literal(right)?;
u32::try_from(shift)
.ok()
.and_then(|shift| base.checked_shl(shift))
}
_ => None,
}
}
fn rename(variant: &syn::Variant, bit: &mut FlagBit, mode: Mode, errors: &mut Errors) {
attribute::walk(&variant.attrs, errors, |meta, errors| {
if meta.path.is_ident("rename") {
if mode == Mode::Mirror {
match value::parse_literal::<syn::Ident>(
&meta,
"`rename = \"…\"` must be an identifier, in a string literal — on a mirror it names the \
UPSTREAM `const` this bit restates, not a word: a flags set stores its bit PATTERN, so \
the words are this declaration's own",
) {
Ok(named) => set_once(
&mut bit.upstream,
named,
&meta.path,
"`rename` is declared more than once — one bit restates one upstream `const`",
errors,
),
Err(e) => errors.push(e),
}
return Ok(());
}
match value::literal(
&meta,
"`rename = \"…\"` must be a string literal — the word this bit is spelled with",
) {
Ok(word) => {
wire::refuse_invalid_name(&word.value(), &word, errors);
if wire::is_graphql_name(&word.value())
&& syn::parse_str::<syn::Ident>(&word.value()).is_err()
{
errors.push(syn::Error::new_spanned(
&word,
format!(
"`{}` is not usable as a Rust identifier, and a flag's word becomes one — this \
kind emits it as the `const` a caller writes `Self::{}` to reach. Rust's own \
keywords are the set this rules out",
word.value(),
word.value()
),
));
}
set_once(
&mut bit.rename,
word.value(),
&meta.path,
"`rename` is declared more than once — one declaration names one word",
errors,
);
}
Err(e) => errors.push(e),
}
return Ok(());
}
errors.push(attribute::unknown(
&meta,
"unknown entry in `#[ingraph(…)]` on a flag — a bit takes `rename = \"…\"` and nothing \
else. A flags column stores its BIT PATTERN in every database, so the wire is the only \
face with a word for a per-face block to move",
&["rename"],
));
Ok(())
});
}
fn moved_option_block(attrs: &[syn::Attribute], errors: &mut Errors) {
for attr in attrs.iter().filter(|attr| attr.path().is_ident("ingraph")) {
errors.push(syn::Error::new_spanned(
attr,
"this declaration's options are the MACRO's arguments — write them inside the attribute's \
own parentheses, as `#[ingraph::flags(u32)]`. A separate `#[ingraph(…)]` beside it is the \
derive family's spelling, and nothing reads it here",
));
}
}
fn forwarded(attrs: &[syn::Attribute]) -> Vec<syn::Attribute> {
attrs
.iter()
.filter(|attr| !attr.path().is_ident("ingraph"))
.cloned()
.collect()
}
fn collisions(bits: &[FlagBit], errors: &mut Errors) {
let mut values: BTreeMap<u128, &syn::Ident> = BTreeMap::new();
for bit in bits {
if let Some(first) = values.get(&bit.value) {
errors.push(syn::Error::new_spanned(
&bit.ident,
format!(
"`{}` and `{first}` are both bit `{:#x}` — two names for one bit is one value that reads \
back as two flags, and a client asking for either would be asking the same question",
bit.ident, bit.value
),
));
} else {
values.insert(bit.value, &bit.ident);
}
}
for (what, spelled) in [
("word", bits.iter().map(FlagBit::word).collect::<Vec<_>>()),
("wire field", bits.iter().map(FlagBit::field).collect()),
] {
let mut taken: BTreeMap<&str, &syn::Ident> = BTreeMap::new();
for (bit, word) in bits.iter().zip(&spelled) {
if let Some(first) = taken.get(word.as_str()) {
errors.push(syn::Error::new_spanned(
&bit.ident,
format!(
"`{}` and `{first}` are both `{word}` as a {what} — a flags set spells each bit once, \
or a text form read back names two of them",
bit.ident
),
));
} else {
taken.insert(word, &bit.ident);
}
}
}
}
pub(crate) fn salvage(
input: &syn::DeriveInput,
options: &[syn::Attribute],
) -> proc_macro2::TokenStream {
use quote::quote;
let mut sink = Errors::default();
let Options { krate, width, .. } = self::options(options, &mut sink);
let krate = krate.unwrap_or_else(|| syn::parse_quote!(::ingraph));
let primitive = quote::format_ident!("{}", width.unwrap_or(BitWidth::U32).as_str());
let vis = &input.vis;
let name = &input.ident;
let attrs = forwarded(&input.attrs);
let bits = match &input.data {
syn::Data::Enum(data) => data
.variants
.iter()
.filter(|variant| matches!(variant.fields, syn::Fields::Unit))
.filter_map(|variant| {
let (_, expression) = variant.discriminant.as_ref()?;
let constant = quote::format_ident!(
"{}",
heck::ToShoutySnakeCase::to_shouty_snake_case(
syn::ext::IdentExt::unraw(&variant.ident)
.to_string()
.as_str()
)
);
let forwarded = forwarded(&variant.attrs);
Some(quote! {
#(#forwarded)*
const #constant = (#expression) as ::core::primitive::#primitive;
})
})
.collect::<Vec<_>>(),
_ => Vec::new(),
};
quote! {
#krate::__private::bitflags::bitflags! {
#(#attrs)*
#vis struct #name: ::core::primitive::#primitive {
#(#bits)*
}
}
}
}