mod bits;
mod catalogue;
mod coverage;
mod layout;
mod message;
mod names;
use alloc::format;
use alloc::string::String;
pub(crate) use catalogue::{validate_dispatch, validate_enum};
#[cfg(feature = "walk")]
pub use layout::validate_container;
pub(crate) use layout::validate_layout;
pub(crate) use message::{validate_choice, validate_message};
use crate::{Field, Item, Kind};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Invalid {
Tiling {
covered_bits: u64,
declared_bits: u64,
},
CrossesWord(String),
Stated(String),
UnknownReference(String),
NonIntegerReference(String),
NotAFlagReference(String),
NotANestedLayout(String),
AfterOpenEnd(String),
DuplicateArm(u64),
Field {
at: String,
why: String,
},
Other(String),
}
impl Invalid {
#[must_use]
pub fn field(at: impl AsRef<str>, why: String) -> Self {
Invalid::Field { at: String::from(at.as_ref()), why }
}
}
impl core::fmt::Display for Invalid {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Invalid::Tiling { covered_bits, declared_bits } => {
write!(f, "the fields cover {covered_bits} of the container's {declared_bits} bits")
}
Invalid::CrossesWord(m)
| Invalid::Stated(m)
| Invalid::UnknownReference(m)
| Invalid::NonIntegerReference(m)
| Invalid::NotAFlagReference(m)
| Invalid::NotANestedLayout(m)
| Invalid::AfterOpenEnd(m)
| Invalid::Other(m) => f.write_str(m),
Invalid::Field { at, why } => write!(f, "field `{at}`: {why}"),
Invalid::DuplicateArm(v) => write!(f, "two arms have the value {v}"),
}
}
}
impl core::error::Error for Invalid {}
pub fn validate(item: &Item) -> Result<(), Invalid> {
match item {
Item::Layout(l) => validate_layout(l),
Item::Enum(e) => validate_enum(e),
Item::Choice(c) => validate_choice(c),
Item::Dispatch(d) => validate_dispatch(d),
Item::Message(m) => validate_message(m),
#[cfg(feature = "walk")]
Item::Verbatim(_) => Ok(()),
}
}
fn is_ident(name: &str) -> bool {
let mut chars = name.chars();
let Some(first) = chars.next() else { return false };
(first.is_alphabetic() || first == '_')
&& chars.all(|c| c.is_alphanumeric() || c == '_')
&& !matches!(name, "_" | "self" | "Self" | "super" | "crate")
}
#[cfg(feature = "walk")]
fn is_type_path(ty: &str) -> bool {
syn::parse_str::<syn::Path>(ty).is_ok()
}
#[cfg(not(feature = "walk"))]
fn is_type_path(ty: &str) -> bool {
let ty = ty.trim();
let Some(first) = ty.chars().next() else { return false };
if !(first.is_alphabetic() || first == '_' || first == ':') {
return false;
}
let mut depth = 0i32;
for c in ty.chars() {
match c {
'<' => depth += 1,
'>' => {
depth -= 1;
if depth < 0 {
return false;
}
}
c if c.is_alphanumeric() || " _:,'&[];()-".contains(c) => {}
_ => return false,
}
}
depth == 0
}
fn ident(what: &str, name: &str) -> Result<(), Invalid> {
if is_ident(name) {
return Ok(());
}
Err(Invalid::Other(format!(
"{what} `{name}` is not a Rust identifier. Use letters, digits and `_`, \
not starting with a digit"
)))
}
fn type_path(at: &str, what: &str, ty: &str) -> Result<(), Invalid> {
if is_type_path(ty) {
return Ok(());
}
Err(Invalid::field(
at,
format!("{what} `{ty}` is not a Rust type path, such as `crate::wire::Head`"),
))
}
fn kind_paths(at: &str, kind: &Kind) -> Result<(), Invalid> {
match kind {
Kind::Codec { ty, .. } => type_path(at, "the codec type", ty),
Kind::Nested { ty, .. } | Kind::NestedArray { ty, .. } => {
type_path(at, "the nested layout", ty)
}
Kind::Var { ty } => type_path(at, "the `VarCodec` type", ty),
Kind::Msg { ty, .. } => type_path(at, "the nested message", ty),
Kind::Checksum { algorithm, .. } if algorithm.trim().is_empty() => Ok(()),
Kind::Checksum { algorithm, .. } => type_path(at, "the checksum algorithm", algorithm),
Kind::Text { codec: Some(ty), .. } => type_path(at, "the `TextCodec` type", ty),
Kind::Scalar(_) | Kind::Array(..) | Kind::Text { .. } => Ok(()),
}
}
pub(crate) const WIDEST_FIELD: u64 = 128;
pub(crate) const WIDEST_BOUND: u64 = 64;
fn field_names(f: &Field) -> Result<(), Invalid> {
ident("field", &f.name)?;
if let Kind::Scalar(s @ (crate::Scalar::U(_) | crate::Scalar::I(_))) = &f.kind
&& !(1..=WIDEST_FIELD).contains(&s.bits())
{
return Err(Invalid::field(
&f.name,
format!("{} bits wide, and a field reads 1 to {WIDEST_FIELD}", s.bits()),
));
}
if let Some(vis) = &f.visibility
&& !is_visibility(vis)
{
return Err(Invalid::field(
&f.name,
format!("`{vis}` is not a Rust visibility, such as `pub(crate)`"),
));
}
kind_paths(&f.name, &f.kind)
}
#[cfg(feature = "walk")]
fn is_visibility(vis: &str) -> bool {
syn::parse_str::<syn::Visibility>(vis).is_ok()
}
#[cfg(not(feature = "walk"))]
fn is_visibility(vis: &str) -> bool {
matches!(vis, "" | "pub" | "pub(crate)" | "pub(self)" | "pub(super)")
|| (vis.starts_with("pub(in ") && vis.ends_with(')'))
}