Skip to main content

layline_codegen/
validate.rs

1//! Structural rules every model item must pass.
2
3mod 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/// Why an item failed validation.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum Invalid {
24    /// The fields do not cover every bit of the container.
25    Tiling {
26        /// The bits the fields cover.
27        covered_bits: u64,
28        /// The bits the container declares.
29        declared_bits: u64,
30    },
31    /// A words-mode bit field crosses a 16-bit word boundary.
32    CrossesWord(String),
33    /// A field's `#[at]` position does not match its computed position.
34    Stated(String),
35    /// A reference names no earlier field.
36    UnknownReference(String),
37    /// A count, length, offset or switch refers to a field that is not an integer.
38    NonIntegerReference(String),
39    /// A [`Presence::Flag`](crate::Presence::Flag) refers to a field that is not a `bool`.
40    NotAFlagReference(String),
41    /// A dotted reference, as written, reaches into a field that is not a nested layout.
42    NotANestedLayout(String),
43    /// A segment follows one that reads to the end of the body.
44    AfterOpenEnd(String),
45    /// Two arms have the same value.
46    DuplicateArm(u64),
47    /// A refusal about one field.
48    Field {
49        /// The field name.
50        at: String,
51        /// The reason, without the `field` prefix that [`Display`](core::fmt::Display) adds.
52        why: String,
53    },
54    /// Any other refusal.
55    Other(String),
56}
57
58impl Invalid {
59    /// A refusal about the field `at`.
60    #[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
88/// Checks a model item.
89///
90/// Without the `walk` feature, type paths get only a lexical check, so generation can still
91/// refuse a path that passes here.
92///
93/// # Errors
94///
95/// An [`Invalid`] naming the item.
96pub 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/// A lexical approximation of `syn`'s path parser.
122#[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
146/// Refuses a `what` called `name` that is not a Rust identifier.
147fn 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
157/// Refuses a type named by field `at` that is not a Rust type path.
158fn 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
168/// Checks every type path a kind names.
169fn 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        // `check_value` refuses a blank algorithm with its own message.
178        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
185/// Checks a field's name and type paths.
186fn field_names(f: &Field) -> Result<(), Invalid> {
187    ident("field", &f.name)?;
188    if let Some(vis) = &f.visibility
189        && !is_visibility(vis)
190    {
191        return Err(Invalid::field(
192            &f.name,
193            format!("`{vis}` is not a Rust visibility, such as `pub(crate)`"),
194        ));
195    }
196    kind_paths(&f.name, &f.kind)
197}
198
199/// With the `walk` feature on, `syn` parses the visibility. Without it, the spelling is checked.
200#[cfg(feature = "walk")]
201fn is_visibility(vis: &str) -> bool {
202    syn::parse_str::<syn::Visibility>(vis).is_ok()
203}
204
205#[cfg(not(feature = "walk"))]
206fn is_visibility(vis: &str) -> bool {
207    matches!(vis, "" | "pub" | "pub(crate)" | "pub(self)" | "pub(super)")
208        || (vis.starts_with("pub(in ") && vis.ends_with(')'))
209}