1mod bits;
4mod catalogue;
5mod coverage;
6mod layout;
7mod message;
8mod names;
9
10use alloc::format;
11use alloc::string::String;
12
13pub(crate) use catalogue::{validate_dispatch, validate_enum};
14#[cfg(feature = "walk")]
15pub use layout::validate_container;
16pub(crate) use layout::validate_layout;
17pub(crate) use message::{validate_choice, validate_message};
18
19use crate::{Field, Item, Kind};
20
21#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum Invalid {
24 Tiling {
26 covered_bits: u64,
28 declared_bits: u64,
30 },
31 CrossesWord(String),
33 Stated(String),
35 UnknownReference(String),
37 NonIntegerReference(String),
39 NotAFlagReference(String),
41 NotANestedLayout(String),
43 AfterOpenEnd(String),
45 DuplicateArm(u64),
47 Field {
49 at: String,
51 why: String,
53 },
54 Other(String),
56}
57
58impl Invalid {
59 #[must_use]
61 pub fn field(at: impl AsRef<str>, why: String) -> Self {
62 Invalid::Field { at: String::from(at.as_ref()), why }
63 }
64}
65
66impl core::fmt::Display for Invalid {
67 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
68 match self {
69 Invalid::Tiling { covered_bits, declared_bits } => {
70 write!(f, "the fields cover {covered_bits} of the container's {declared_bits} bits")
71 }
72 Invalid::CrossesWord(m)
73 | Invalid::Stated(m)
74 | Invalid::UnknownReference(m)
75 | Invalid::NonIntegerReference(m)
76 | Invalid::NotAFlagReference(m)
77 | Invalid::NotANestedLayout(m)
78 | Invalid::AfterOpenEnd(m)
79 | Invalid::Other(m) => f.write_str(m),
80 Invalid::Field { at, why } => write!(f, "field `{at}`: {why}"),
81 Invalid::DuplicateArm(v) => write!(f, "two arms have the value {v}"),
82 }
83 }
84}
85
86impl core::error::Error for Invalid {}
87
88pub fn validate(item: &Item) -> Result<(), Invalid> {
97 match item {
98 Item::Layout(l) => validate_layout(l),
99 Item::Enum(e) => validate_enum(e),
100 Item::Choice(c) => validate_choice(c),
101 Item::Dispatch(d) => validate_dispatch(d),
102 Item::Message(m) => validate_message(m),
103 #[cfg(feature = "walk")]
104 Item::Verbatim(_) => Ok(()),
105 }
106}
107
108fn is_ident(name: &str) -> bool {
109 let mut chars = name.chars();
110 let Some(first) = chars.next() else { return false };
111 (first.is_alphabetic() || first == '_')
112 && chars.all(|c| c.is_alphanumeric() || c == '_')
113 && !matches!(name, "_" | "self" | "Self" | "super" | "crate")
114}
115
116#[cfg(feature = "walk")]
117fn is_type_path(ty: &str) -> bool {
118 syn::parse_str::<syn::Path>(ty).is_ok()
119}
120
121#[cfg(not(feature = "walk"))]
123fn is_type_path(ty: &str) -> bool {
124 let ty = ty.trim();
125 let Some(first) = ty.chars().next() else { return false };
126 if !(first.is_alphabetic() || first == '_' || first == ':') {
127 return false;
128 }
129 let mut depth = 0i32;
130 for c in ty.chars() {
131 match c {
132 '<' => depth += 1,
133 '>' => {
134 depth -= 1;
135 if depth < 0 {
136 return false;
137 }
138 }
139 c if c.is_alphanumeric() || " _:,'&[];()-".contains(c) => {}
140 _ => return false,
141 }
142 }
143 depth == 0
144}
145
146fn ident(what: &str, name: &str) -> Result<(), Invalid> {
148 if is_ident(name) {
149 return Ok(());
150 }
151 Err(Invalid::Other(format!(
152 "{what} `{name}` is not a Rust identifier. Use letters, digits and `_`, \
153 not starting with a digit"
154 )))
155}
156
157fn type_path(at: &str, what: &str, ty: &str) -> Result<(), Invalid> {
159 if is_type_path(ty) {
160 return Ok(());
161 }
162 Err(Invalid::field(
163 at,
164 format!("{what} `{ty}` is not a Rust type path, such as `crate::wire::Head`"),
165 ))
166}
167
168fn kind_paths(at: &str, kind: &Kind) -> Result<(), Invalid> {
170 match kind {
171 Kind::Codec { ty, .. } => type_path(at, "the codec type", ty),
172 Kind::Nested { ty, .. } | Kind::NestedArray { ty, .. } => {
173 type_path(at, "the nested layout", ty)
174 }
175 Kind::Var { ty } => type_path(at, "the `VarCodec` type", ty),
176 Kind::Msg { ty, .. } => type_path(at, "the nested message", ty),
177 Kind::Checksum { algorithm, .. } if algorithm.trim().is_empty() => Ok(()),
179 Kind::Checksum { algorithm, .. } => type_path(at, "the checksum algorithm", algorithm),
180 Kind::Text { codec: Some(ty), .. } => type_path(at, "the `TextCodec` type", ty),
181 Kind::Scalar(_) | Kind::Array(..) | Kind::Text { .. } => Ok(()),
182 }
183}
184
185pub(crate) const WIDEST_FIELD: u64 = 128;
187
188pub(crate) const WIDEST_BOUND: u64 = 64;
190
191fn field_names(f: &Field) -> Result<(), Invalid> {
193 ident("field", &f.name)?;
194 if let Kind::Scalar(s @ (crate::Scalar::U(_) | crate::Scalar::I(_))) = &f.kind
195 && !(1..=WIDEST_FIELD).contains(&s.bits())
196 {
197 return Err(Invalid::field(
198 &f.name,
199 format!("{} bits wide, and a field reads 1 to {WIDEST_FIELD}", s.bits()),
200 ));
201 }
202 if let Some(vis) = &f.visibility
203 && !is_visibility(vis)
204 {
205 return Err(Invalid::field(
206 &f.name,
207 format!("`{vis}` is not a Rust visibility, such as `pub(crate)`"),
208 ));
209 }
210 kind_paths(&f.name, &f.kind)
211}
212
213#[cfg(feature = "walk")]
215fn is_visibility(vis: &str) -> bool {
216 syn::parse_str::<syn::Visibility>(vis).is_ok()
217}
218
219#[cfg(not(feature = "walk"))]
220fn is_visibility(vis: &str) -> bool {
221 matches!(vis, "" | "pub" | "pub(crate)" | "pub(self)" | "pub(super)")
222 || (vis.starts_with("pub(in ") && vis.ends_with(')'))
223}