use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote};
use syn::parse::Parser;
use syn::punctuated::Punctuated;
use syn::{Error, Expr, ExprLit, GenericArgument, Ident, Lit, Meta, PathArguments, Token, Type};
#[derive(Clone, Copy, PartialEq)]
pub(crate) enum Mode {
Plain,
Rc,
RcWeak,
}
#[derive(Clone, Copy, PartialEq)]
pub(crate) enum Kind {
Owned,
Strong,
Weak,
Ref,
Embed,
Pod,
}
pub(crate) struct VecInfo {
pub(crate) elem: TokenStream,
pub(crate) is_string: bool,
}
pub(crate) fn is_str(ty: &Type) -> bool {
matches!(ty, Type::Path(tp) if tp.path.segments.last().is_some_and(|s| s.ident == "str"))
}
pub(crate) fn tokens_mention(ts: TokenStream, params: &[&Ident]) -> bool {
ts.into_iter().any(|t| match t {
proc_macro2::TokenTree::Ident(id) => params.iter().any(|p| **p == id),
proc_macro2::TokenTree::Group(g) => tokens_mention(g.stream(), params),
_ => false,
})
}
pub(crate) fn type_mentions_any(ty: &Type, params: &[&Ident]) -> bool {
tokens_mention(quote!(#ty), params)
}
pub(crate) fn reject_nested_const_dims(
dims: &[&Expr],
const_params: &[&Ident],
span: &Type,
) -> syn::Result<()> {
if dims.len() > 1
&& !const_params.is_empty()
&& dims
.iter()
.any(|d| tokens_mention(quote!(#d), const_params))
{
return Err(Error::new_spanned(
span,
"[BSTACK0407] a nested array `[[T; N]; M]` with a const-parameter dimension is not supported: \
its flattened length would be a const expression (`N * M`), which stable Rust \
forbids from using a generic parameter. Use a single `[T; N]`, or make the \
dimensions concrete.",
));
}
Ok(())
}
pub(crate) fn vec_inner(ty: &Type) -> Option<&Type> {
let Type::Path(tp) = ty else {
return None;
};
let seg = tp.path.segments.last()?;
if seg.ident != "Vec" {
return None;
}
let PathArguments::AngleBracketed(ab) = &seg.arguments else {
return None;
};
match ab.args.first()? {
GenericArgument::Type(inner) => Some(inner),
_ => None,
}
}
pub(crate) fn param_stored_inline(ty: &Type, param: &Ident) -> bool {
if vec_inner(ty).is_some() {
return false;
}
if let Some(inner) = option_inner(ty) {
return param_stored_inline(inner, param);
}
match ty {
Type::Array(a) => param_stored_inline(&a.elem, param),
Type::Tuple(t) => t.elems.iter().any(|e| param_stored_inline(e, param)),
Type::Paren(p) => param_stored_inline(&p.elem, param),
Type::Group(g) => param_stored_inline(&g.elem, param),
other => type_mentions_any(other, &[param]),
}
}
pub(crate) fn err_double_option(ty: &Type) -> Error {
Error::new_spanned(
ty,
"[BSTACK0101] nested `Option<Option<T>>` is not supported: a field / `Vec` slot lowers a \
single `Option` to the absent/`0` niche, and a second layer has nowhere to \
live on disk. Model the states explicitly with a `#[bstack_enum]`, e.g. \
`enum Slot { Missing, Empty, Present(T) }`.",
)
}
pub(crate) fn err_vec_in_vec(ty: &Type) -> Error {
Error::new_spanned(
ty,
"[BSTACK0102] nested `Vec<Vec<T>>` / `Vec<String>` is not supported: a `Vec` field stores one \
inline descriptor whose elements are a single leaf (POD or a block reference), \
not another dynamically-sized region. Wrap the inner vector in an explicit \
`#[bstack_block]` struct and store `Vec<ThatStruct>` (annotating the element \
per its ownership).",
)
}
pub(crate) fn err_tuple_in_vec(ty: &Type) -> Error {
Error::new_spanned(
ty,
"[BSTACK0103] a tuple is not supported as a `Vec` element: a `Vec` element must be a single \
leaf — POD, or a block reference — and a tuple (a POD one has no `Vec` layout, \
a `(ref, pod)` one cannot be split into offset + inline bytes) is neither. Wrap \
it in a named `#[bstack_block]` struct and store `Vec<ThatStruct>` (annotating \
each reference field inside it, leaving POD fields plain).",
)
}
pub(crate) fn check_container_nesting(ty: &Type) -> syn::Result<()> {
if let Some(inner) = option_inner(ty) {
if option_inner(inner).is_some() {
return Err(err_double_option(ty));
}
return check_bare(inner);
}
check_bare(ty)
}
pub(crate) fn check_bare(ty: &Type) -> syn::Result<()> {
if let Some(elem) = vec_inner(ty) {
return check_vec_elem(elem);
}
Ok(())
}
pub(crate) fn check_vec_elem(ty: &Type) -> syn::Result<()> {
let mut ty = ty;
while let Type::Array(a) = ty {
ty = &a.elem;
}
if let Some(inner) = option_inner(ty) {
if option_inner(inner).is_some() {
return Err(err_double_option(ty));
}
if vec_info(inner).is_some() {
return Err(err_vec_in_vec(ty));
}
if let Type::Tuple(_) = inner {
return Err(err_tuple_in_vec(inner));
}
return Ok(());
}
if vec_info(ty).is_some() {
return Err(err_vec_in_vec(ty));
}
if let Type::Tuple(_) = ty {
return Err(err_tuple_in_vec(ty));
}
Ok(())
}
pub(crate) fn vec_info(ty: &Type) -> Option<VecInfo> {
let Type::Path(tp) = ty else {
return None;
};
let seg = tp.path.segments.last()?;
if seg.ident == "String" {
return Some(VecInfo {
elem: quote!(u8),
is_string: true,
});
}
if seg.ident == "Vec"
&& let PathArguments::AngleBracketed(ab) = &seg.arguments
&& let Some(GenericArgument::Type(inner)) = ab.args.first()
{
return Some(VecInfo {
elem: quote!(#inner),
is_string: false,
});
}
None
}
pub(crate) fn option_inner(ty: &Type) -> Option<&Type> {
let Type::Path(tp) = ty else {
return None;
};
let seg = tp.path.segments.last()?;
if seg.ident != "Option" {
return None;
}
let PathArguments::AngleBracketed(ab) = &seg.arguments else {
return None;
};
match ab.args.first()? {
GenericArgument::Type(inner) => Some(inner),
_ => None,
}
}
pub(crate) fn validate_foreign_target(
kind: Kind,
ftarget: &Type,
span: &Type,
what: &str,
assert_name: Ident,
emit_assert: bool,
wrapper_defs: &mut Vec<TokenStream>,
) -> syn::Result<()> {
match kind {
Kind::Owned | Kind::Strong | Kind::Weak | Kind::Ref => {}
Kind::Pod => {
return Err(Error::new_spanned(
span,
format!(
"[BSTACK0302] {what} needs an ownership annotation naming the target's kind \
(`#[bstack_owned/strong/weak/ref]`); a bare foreign pointer targets a block"
),
));
}
Kind::Embed => {
return Err(Error::new_spanned(
span,
"[BSTACK0301] `Foreign<T>` is a pointer and cannot be `#[embed]`ed",
));
}
}
reject_bad_foreign_target(ftarget, span, what)?;
if emit_assert {
wrapper_defs.push(quote! {
#[doc(hidden)]
const _: fn() = {
fn #assert_name<__T: ::bstack_raii::BStackBlock>() {}
#assert_name::<#ftarget>
};
});
}
Ok(())
}
pub(crate) fn reject_bad_foreign_target(
ftarget: &Type,
span: &Type,
what: &str,
) -> syn::Result<()> {
let bridge = "bridge it inside an explicit `#[bstack_block]` struct and point the \
`Foreign` at that struct";
if foreign_inner(ftarget).is_some() {
return Err(Error::new_spanned(
span,
format!(
"[BSTACK0303] {what}: a `Foreign` cannot point at another `Foreign` — a pointer to a \
pointer is not allowed. {bridge}. (A collection OF pointers such as \
`Vec<Foreign<T>>` / `[Foreign<T>; N]` IS allowed; it is a pointer TO a \
pointer/collection that is not.)"
),
));
}
if let Some(inner) = option_inner(ftarget) {
if foreign_inner(inner).is_some() {
return Err(Error::new_spanned(
span,
format!(
"[BSTACK0304] {what}: `Foreign<Option<Foreign<T>>>` is a double `Foreign` (a pointer to a \
nullable pointer). {bridge}."
),
));
}
return Err(Error::new_spanned(
span,
format!(
"[BSTACK0305] {what}: use `Option<Foreign<T>>` for a nullable foreign pointer, not \
`Foreign<Option<T>>` — nullability belongs on the field/element, and a null \
element is a `Foreign` with offset 0, not a pointer to a nullable value."
),
));
}
if vec_info(ftarget).is_some() || is_str(ftarget) {
return Err(Error::new_spanned(
span,
format!(
"[BSTACK0306] {what}: a `Foreign` target must be a `#[bstack_block]`, not a `Vec` / `String`. \
`Vec<Foreign<T>>` (a vector OF pointers) is allowed, but `Foreign<Vec<T>>` (a \
pointer TO a vector) is not — {bridge}."
),
));
}
if let Type::Array(_) = ftarget {
return Err(Error::new_spanned(
span,
format!(
"[BSTACK0307] {what}: a `Foreign` target must be a `#[bstack_block]`, not an array. \
`[Foreign<T>; N]` (an array OF pointers) is allowed, but `Foreign<[T; N]>` is \
not — {bridge}."
),
));
}
if let Type::Tuple(_) = ftarget {
return Err(Error::new_spanned(
span,
format!(
"[BSTACK0308] {what}: a `Foreign` target must be a `#[bstack_block]`, not a tuple — {bridge}."
),
));
}
Ok(())
}
pub(crate) fn field_foreign_target(ty: &Type) -> Option<&Type> {
let t = option_inner(ty).unwrap_or(ty);
if let Some(x) = foreign_inner(t) {
return Some(x);
}
if let Some(ve) = vec_inner(t) {
let ve = option_inner(ve).unwrap_or(ve);
if let Some(x) = foreign_inner(ve) {
return Some(x);
}
}
if let Type::Array(_) = t {
let mut cur = t;
while let Type::Array(a) = cur {
cur = &a.elem;
}
let cur = option_inner(cur).unwrap_or(cur);
if let Some(x) = foreign_inner(cur) {
return Some(x);
}
}
if let Type::Tuple(tup) = t {
for e in &tup.elems {
let e = option_inner(e).unwrap_or(e);
if let Some(x) = foreign_inner(e) {
return Some(x);
}
}
}
None
}
pub(crate) fn foreign_targets_in(ty: &Type) -> Vec<&Type> {
let mut out = Vec::new();
collect_foreign_targets(ty, &mut out);
out
}
pub(crate) fn collect_foreign_targets<'a>(ty: &'a Type, out: &mut Vec<&'a Type>) {
let t = option_inner(ty).unwrap_or(ty);
if let Some(x) = foreign_inner(t) {
out.push(x);
return;
}
if let Some(ve) = vec_inner(t) {
collect_foreign_targets(ve, out);
return;
}
if let Type::Array(_) = t {
let mut cur = t;
while let Type::Array(a) = cur {
cur = &a.elem;
}
collect_foreign_targets(cur, out);
return;
}
if let Type::Tuple(tup) = t {
for e in &tup.elems {
collect_foreign_targets(e, out);
}
}
}
pub(crate) fn foreign_inner(ty: &Type) -> Option<&Type> {
let Type::Path(tp) = ty else {
return None;
};
let seg = tp.path.segments.last()?;
if seg.ident != "Foreign" {
return None;
}
let PathArguments::AngleBracketed(ab) = &seg.arguments else {
return None;
};
match ab.args.first()? {
GenericArgument::Type(inner) => Some(inner),
_ => None,
}
}
pub(crate) fn array_shape(ty: &Type) -> syn::Result<(Vec<&Expr>, &Type, bool)> {
let mut dims: Vec<&Expr> = Vec::new();
let mut cur = ty;
while let Type::Array(a) = cur {
if let Expr::Lit(ExprLit {
lit: Lit::Int(n), ..
}) = &a.len
&& n.base10_parse::<u64>().ok() == Some(0)
{
return Err(Error::new_spanned(
&a.len,
"[BSTACK0112] a zero-length array dimension is not supported",
));
}
dims.push(&a.len);
cur = &a.elem;
}
let (leaf, nullable) = match option_inner(cur) {
Some(inner) => (inner, true),
None => (cur, false),
};
if let Type::Array(_) = leaf {
return Err(Error::new_spanned(
cur,
"[BSTACK0104] `Option` wrapping a whole sub-array is not supported; move the \
`Option` onto the leaf element, e.g. `[[Option<T>; N]; M]`",
));
}
Ok((dims, leaf, nullable))
}
pub(crate) fn dims_prod(dims: &[&Expr]) -> TokenStream {
if dims.is_empty() {
return quote!(1usize);
}
let first = dims[0];
let mut t = quote!(#first);
for d in &dims[1..] {
t = quote!(#t * (#d));
}
t
}
pub(crate) fn nested_ty(dims: &[&Expr], leaf: &TokenStream) -> TokenStream {
if dims.is_empty() {
return leaf.clone();
}
let d = dims[0];
let inner = nested_ty(&dims[1..], leaf);
quote!([#inner; #d])
}
pub(crate) fn nested_build(
dims: &[&Expr],
leaf_ty: &TokenStream,
leaf_read: &dyn Fn(&Ident) -> TokenStream,
) -> TokenStream {
let k = format_ident!("__k");
let body = nested_build_inner(dims, leaf_ty, 0, &k, leaf_read);
quote!({ let mut #k = 0usize; #body })
}
pub(crate) fn nested_build_inner(
dims: &[&Expr],
leaf_ty: &TokenStream,
depth: usize,
k: &Ident,
leaf_read: &dyn Fn(&Ident) -> TokenStream,
) -> TokenStream {
if dims.is_empty() {
let val = leaf_read(k);
return quote!({ let __e = #val; #k += 1; __e });
}
let d = dims[0];
let rest = &dims[1..];
let vv = format_ident!("__bv{depth}");
let inner_ty = nested_ty(rest, leaf_ty);
let body = nested_build_inner(rest, leaf_ty, depth + 1, k, leaf_read);
quote!({
let mut #vv = ::std::vec::Vec::with_capacity(#d);
for _ in 0usize..(#d) {
#vv.push(#body);
}
match <[#inner_ty; #d]>::try_from(#vv) {
::std::result::Result::Ok(__a) => __a,
::std::result::Result::Err(_) => unreachable!(),
}
})
}
pub(crate) fn nested_consume(
dims: &[&Expr],
val: &TokenStream,
leaf_write: &dyn Fn(&Ident, &Ident) -> TokenStream,
) -> TokenStream {
let k = format_ident!("__k");
let body = nested_consume_inner(dims, val, 0, &k, leaf_write);
quote!({ let mut #k = 0usize; #body })
}
pub(crate) fn nested_consume_inner(
dims: &[&Expr],
val: &TokenStream,
depth: usize,
k: &Ident,
leaf_write: &dyn Fn(&Ident, &Ident) -> TokenStream,
) -> TokenStream {
if dims.is_empty() {
let leaf = format_ident!("__leaf");
let w = leaf_write(k, &leaf);
return quote!({ let #leaf = #val; #w #k += 1; });
}
let rest = &dims[1..];
let cv = format_ident!("__cn{depth}");
let inner = nested_consume_inner(rest, "e!(#cv), depth + 1, k, leaf_write);
quote!(for #cv in #val { #inner })
}
pub(crate) struct Attr {
pub(crate) mode: Mode,
pub(crate) tag: Option<String>,
pub(crate) ctrl_tag: Option<String>,
pub(crate) allow_overlong: bool,
pub(crate) allow_coerced_ref: bool,
pub(crate) repr: Option<String>,
}
pub(crate) fn parse_attr(attr: TokenStream) -> syn::Result<Attr> {
let (mut rc, mut weak) = (false, false);
let mut tag = None;
let mut ctrl_tag = None;
let mut allow_overlong = false;
let mut allow_coerced_ref = false;
let mut repr = None;
if !attr.is_empty() {
let metas = Punctuated::<Meta, Token![,]>::parse_terminated.parse2(attr)?;
for meta in metas {
match &meta {
Meta::Path(p) => match ident_of(p).as_deref() {
Some("rc") => rc = true,
Some("weak") => weak = true,
_ => return Err(Error::new_spanned(&meta, unknown_opt())),
},
Meta::NameValue(nv) => {
let value = match &nv.value {
Expr::Lit(ExprLit {
lit: Lit::Str(s), ..
}) => s.value(),
other => {
return Err(Error::new_spanned(
other,
"[BSTACK0004] expected a string literal",
));
}
};
match ident_of(&nv.path).as_deref() {
Some("tag") => tag = Some(value),
Some("ctrl_tag") => ctrl_tag = Some(value),
_ => return Err(Error::new_spanned(&meta, unknown_opt())),
}
}
Meta::List(list) if list.path.is_ident("repr") => {
let r: Ident = list.parse_args().map_err(|_| {
Error::new_spanned(
list,
"[BSTACK0005] expected `repr(u8|u16|u32|u64|i8|i16|i32|i64|aligned)`",
)
})?;
repr = Some(match r.to_string().as_str() {
"aligned" => "u64".to_string(),
name @ ("u8" | "u16" | "u32" | "u64" | "i8" | "i16" | "i32" | "i64") => {
name.to_string()
}
"usize" | "isize" => {
return Err(Error::new_spanned(
&r,
"[BSTACK0006] `repr(usize)` / `repr(isize)` are not allowed — bstack offsets \
are 64-bit, so pick an explicit width (e.g. `repr(u64)`)",
));
}
_ => {
return Err(Error::new_spanned(
&r,
"[BSTACK0005] expected `u8|u16|u32|u64|i8|i16|i32|i64|aligned`",
));
}
});
}
Meta::List(list) if list.path.is_ident("allow") => {
let lints =
list.parse_args_with(Punctuated::<Ident, Token![,]>::parse_terminated)?;
for lint in lints {
match lint.to_string().as_str() {
"overlong_tag" => allow_overlong = true,
"coerced_ref" => allow_coerced_ref = true,
"deprecated" => {
allow_overlong = true;
allow_coerced_ref = true;
}
_ => {
return Err(Error::new_spanned(
&lint,
"[BSTACK0007] expected `overlong_tag`, `coerced_ref`, or `deprecated`",
));
}
}
}
}
_ => return Err(Error::new_spanned(&meta, unknown_opt())),
}
}
}
let mode = match (rc, weak) {
(false, false) => Mode::Plain,
(true, false) => Mode::Rc,
(true, true) => Mode::RcWeak,
(false, true) => {
return Err(Error::new(
Span::call_site(),
"[BSTACK0002] `weak` requires `rc` (use `rc, weak`)",
));
}
};
Ok(Attr {
mode,
tag,
ctrl_tag,
allow_overlong,
allow_coerced_ref,
repr,
})
}
pub(crate) fn ident_of(path: &syn::Path) -> Option<String> {
path.get_ident().map(|i| i.to_string())
}
pub(crate) fn is_allow_deprecated(attr: &syn::Attribute) -> bool {
attr.path().is_ident("allow")
&& attr
.parse_args_with(Punctuated::<Ident, Token![,]>::parse_terminated)
.is_ok_and(|lints| lints.iter().any(|l| l == "deprecated"))
}
pub(crate) fn unknown_opt() -> &'static str {
"[BSTACK0003] expected `rc`, `weak`, `tag = \"...\"`, `ctrl_tag = \"...\"`, `allow(...)`, or (enums) `repr(...)`"
}
pub(crate) struct Tag {
pub(crate) bytes: [u8; 8],
pub(crate) truncated: bool,
}
pub(crate) fn fnv1a64(s: &str) -> u64 {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for b in s.bytes() {
h ^= b as u64;
h = h.wrapping_mul(0x0000_0100_0000_01b3);
}
h
}
pub(crate) fn build_tag(hash: u64, prefix: &[u8]) -> Tag {
let mut bytes = hash.to_le_bytes();
for b in bytes.iter_mut() {
*b |= 0x80;
}
let truncated = prefix.len() > 8;
let n = prefix.len().min(8);
bytes[..n].copy_from_slice(&prefix[..n]);
Tag { bytes, truncated }
}
pub(crate) fn is_ascii_vowel(b: u8) -> bool {
matches!(
b.to_ascii_uppercase(),
b'A' | b'E' | b'I' | b'O' | b'U' | b'Y'
)
}
pub(crate) fn split_words(name: &str) -> Vec<String> {
let chars: Vec<char> = name.chars().collect();
let mut words = Vec::new();
let mut cur = String::new();
for (i, &c) in chars.iter().enumerate() {
if !c.is_alphanumeric() {
if !cur.is_empty() {
words.push(std::mem::take(&mut cur));
}
continue;
}
let boundary = !cur.is_empty()
&& ((c.is_uppercase() && chars[i - 1].is_lowercase())
|| (c.is_uppercase()
&& chars[i - 1].is_uppercase()
&& chars.get(i + 1).is_some_and(|n| n.is_lowercase())));
if boundary {
words.push(std::mem::take(&mut cur));
}
cur.push(c);
}
if !cur.is_empty() {
words.push(cur);
}
words
}
pub(crate) fn auto_prefix(name: &str) -> Vec<u8> {
let words = split_words(name);
let prefix: Vec<u8> = if words.len() >= 2 {
words
.iter()
.filter_map(|w| w.bytes().next())
.map(|b| b.to_ascii_uppercase())
.take(4)
.collect()
} else {
let letters: Vec<u8> = words
.first()
.map(|w| {
w.bytes()
.filter(u8::is_ascii_alphanumeric)
.map(|b| b.to_ascii_uppercase())
.collect()
})
.unwrap_or_default();
let mut v = Vec::new();
for (i, &b) in letters.iter().enumerate() {
if i == 0 || !is_ascii_vowel(b) {
v.push(b);
}
if v.len() == 4 {
break;
}
}
if v.len() < 2 {
v = letters.into_iter().take(2).collect();
}
v
};
prefix
}
pub(crate) fn eightcc_expr(bytes: &[u8; 8]) -> TokenStream {
let bytes = bytes.iter();
quote!(::bstack_raii::EightCC::new([#(#bytes),*]))
}
pub(crate) fn ctrl_eightcc(
ctrl_tag: Option<&String>,
hash: u64,
data_tag: &Tag,
data_eightcc: &TokenStream,
ident: &Ident,
) -> syn::Result<(TokenStream, bool)> {
match ctrl_tag {
None => Ok((quote!(#data_eightcc.with_ctrl_bit()), false)),
Some(t) => {
let ctrl_prefix = t.bytes().collect::<Vec<u8>>();
let ctrl_tag = build_tag(hash, &ctrl_prefix);
if ctrl_tag.bytes == data_tag.bytes {
return Err(Error::new_spanned(
ident,
"[BSTACK0006] the explicit `ctrl_tag` equals the data tag — a \
control block would then pass every data-block identity check; \
choose a distinct `ctrl_tag` (or omit it to auto-derive one)",
));
}
let ctrl_base = eightcc_expr(&ctrl_tag.bytes);
Ok((
quote!(#ctrl_base.mix_str(::core::module_path!())),
ctrl_tag.truncated,
))
}
}
}
pub(crate) fn deprecation_warning(warn_fn: &Ident, lint: &Ident, msg: &str) -> TokenStream {
quote! {
#[doc(hidden)]
#[allow(dead_code, non_snake_case)]
fn #warn_fn() {
#[deprecated(note = #msg)]
fn #lint() {}
#lint();
}
}
}
pub(crate) fn classify_attrs(attrs: &[syn::Attribute]) -> syn::Result<Kind> {
let mut found: Option<Kind> = None;
for attr in attrs {
let Some(id) = attr.path().get_ident() else {
continue;
};
if id == "cfg" || id == "cfg_attr" {
return Err(Error::new_spanned(
attr,
"[BSTACK0004] `#[cfg]` / `#[cfg_attr]` on a bstack block field or \
variant is unsupported: the generated on-disk layout, constructor, \
and accessors cannot be made conditional, so the attribute would be \
silently ignored rather than honoured",
));
}
let name = id.to_string();
let kind = match name.as_str() {
"bstack_owned" => Kind::Owned,
"bstack_strong" => Kind::Strong,
"bstack_weak" => Kind::Weak,
"bstack_ref" => Kind::Ref,
"embed" => Kind::Embed,
"bstack_mut" | "bstack_static" => continue,
_ if name.starts_with("bstack_") || name.starts_with("embed") => {
return Err(Error::new_spanned(
attr,
format!(
"[BSTACK0003] unrecognised bstack attribute `{name}` — expected one of \
`bstack_owned`, `bstack_strong`, `bstack_weak`, `bstack_ref`, `embed`, \
`bstack_mut`, `bstack_static`"
),
));
}
_ => continue,
};
if found.is_some() {
return Err(Error::new_spanned(
attr,
"[BSTACK0001] at most one bstack ownership annotation is allowed here",
));
}
found = Some(kind);
}
Ok(found.unwrap_or(Kind::Pod))
}
pub(crate) fn classify(field: &syn::Field) -> syn::Result<Kind> {
classify_attrs(&field.attrs)
}
pub(crate) fn is_bstack_mut(attrs: &[syn::Attribute]) -> bool {
attrs
.iter()
.filter_map(|a| a.path().get_ident())
.any(|id| id == "bstack_mut")
}
pub(crate) fn is_default_variant(attrs: &[syn::Attribute]) -> bool {
attrs
.iter()
.filter_map(|a| a.path().get_ident())
.any(|id| id == "default")
}
pub(crate) fn is_bstack_static(attrs: &[syn::Attribute]) -> bool {
attrs
.iter()
.filter_map(|a| a.path().get_ident())
.any(|id| id == "bstack_static")
}
pub(crate) fn bstack_static_expr(attrs: &[syn::Attribute]) -> Option<syn::Result<syn::Expr>> {
attrs
.iter()
.find(|a| a.path().is_ident("bstack_static"))
.map(|a| a.parse_args::<syn::Expr>())
}
pub(crate) fn parse_disc_expr(expr: &Expr) -> syn::Result<i128> {
match expr {
Expr::Lit(ExprLit {
lit: Lit::Int(li), ..
}) => li.base10_parse::<i128>(),
Expr::Unary(syn::ExprUnary {
op: syn::UnOp::Neg(_),
expr,
..
}) => match &**expr {
Expr::Lit(ExprLit {
lit: Lit::Int(li), ..
}) => Ok(-li.base10_parse::<i128>()?),
other => Err(Error::new_spanned(
other,
"[BSTACK0204] expected an integer literal discriminant",
)),
},
other => Err(Error::new_spanned(
other,
"[BSTACK0204] expected an integer literal discriminant",
)),
}
}
pub(crate) fn int_bounds(ty: &str) -> (i128, i128) {
match ty {
"u8" => (0, u8::MAX as i128),
"u16" => (0, u16::MAX as i128),
"u32" => (0, u32::MAX as i128),
"u64" => (0, u64::MAX as i128),
"i8" => (i8::MIN as i128, i8::MAX as i128),
"i16" => (i16::MIN as i128, i16::MAX as i128),
"i32" => (i32::MIN as i128, i32::MAX as i128),
"i64" => (i64::MIN as i128, i64::MAX as i128),
_ => unreachable!("discriminant repr is validated in parse_attr"),
}
}
pub(crate) fn infer_disc_ty(min: i128, max: i128) -> &'static str {
let candidates: [&str; 4] = if min < 0 {
["i8", "i16", "i32", "i64"]
} else {
["u8", "u16", "u32", "u64"]
};
for ty in candidates {
let (lo, hi) = int_bounds(ty);
if min >= lo && max <= hi {
return ty;
}
}
candidates[3] }