Skip to main content

zenkey_model/
words.rs

1//! Words by table: what the profiles whose records carry an index where
2//! an earlier major carried text have in common (`desired.v2` §2.10,
3//! `health.v2` §2.10; #986's Q2).
4//!
5//! A record's field holds a number, a contract's annotation holds a list,
6//! and the entry at that number is the word. A number the list in hand
7//! does not reach is shown as the number, and one reserved code says the
8//! writer's table held no such word:
9//!
10//! ```text
11//! list(value, max, entry, once) ─▶ an annotation's value as a table: a list of strings, or none
12//! Index::at(i, max)             ─▶ a place in a table as a record carries it, or out_of_range
13//! write(table, word, max)       ─▶ the index of a word its table holds, else out_of_range
14//! read(table, index)            ─▶ the entry │ the number, past the table or with none in hand │ out_of_range
15//! uses(contract, profile)       ─▶ whether the contract may declare that profile's tables
16//! instance_table(named)         ─▶ an instance's table among the revisions its descriptor names: none │ the one │ differ
17//! Lint                          ─▶ one finding of a profile's lint of a contract's tables
18//! ```
19//!
20//! What a number means stays each profile's: `desired.v2`'s two tables are
21//! a report resource's, indexed from 0 to 254, and `health.v2`'s three are
22//! an instance's, in the upper half of a 6-bit word under the profile's
23//! own names. So does each profile's `Major`, which reads a contract's
24//! `uses` for one and a descriptor's `interfaces` for the other. An
25//! instance's table ([`Instance`]) is `health.v2`'s and `alarms.v2`'s, over
26//! a list of names for one and of rules for the other.
27
28use serde_json::{Value, json};
29
30use crate::contract::{Contract, Resource};
31use crate::packed::WriteRefusal;
32
33/// The reserved word of a field that holds an index: the writer's table
34/// did not hold the word (core §7.6's reserved code, by its name).
35pub const OUT_OF_RANGE: &str = "out_of_range";
36
37/// Whether a contract lists `profile` in `uses`: one that may declare
38/// that profile's tables (core §10).
39#[must_use]
40pub fn uses(c: &Contract, profile: &str) -> bool {
41    c.uses.iter().any(|u| u.to_string() == profile)
42}
43
44/// An index into a table, as a record carries it.
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
46pub enum Index {
47    /// An entry's place in its table, from 0.
48    At(u8),
49    /// A word the writer's table does not hold.
50    OutOfRange,
51}
52
53impl Index {
54    /// The place `i` of a table whose greatest index is `max`:
55    /// `out_of_range` above it, where a record has no code for the place.
56    #[must_use]
57    pub fn at(i: usize, max: u8) -> Index {
58        match u8::try_from(i) {
59            Ok(i) if i <= max => Index::At(i),
60            _ => Index::OutOfRange,
61        }
62    }
63
64    /// Core §7.6's JSON reading: the number, or the reserved code's name.
65    #[must_use]
66    pub fn to_json(self) -> Value {
67        match self {
68            Index::At(i) => json!(i),
69            Index::OutOfRange => json!(OUT_OF_RANGE),
70        }
71    }
72
73    /// [`Index::to_json`] read back.
74    ///
75    /// # Errors
76    /// [`WriteRefusal::Range`] for a number that is no `u8`, and
77    /// [`WriteRefusal::Value`] for any other value.
78    pub fn of_json(v: &Value) -> Result<Index, WriteRefusal> {
79        match v {
80            Value::String(s) if s == OUT_OF_RANGE => Ok(Index::OutOfRange),
81            Value::Number(n) => n
82                .as_u64()
83                .and_then(|i| u8::try_from(i).ok())
84                .map(Index::At)
85                .ok_or(WriteRefusal::Range),
86            _ => Err(WriteRefusal::Value),
87        }
88    }
89}
90
91/// What an index reads as, with the table a reader holds.
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93pub enum Word<'a> {
94    /// The table's entry.
95    Entry(&'a str),
96    /// An index past the table the reader holds, a later revision's, or
97    /// any index with no table in hand: shown as its number.
98    Number(u8),
99    /// `out_of_range`: the writer's table did not hold the word. A reader
100    /// shows that, never an entry.
101    OutOfRange,
102}
103
104/// The word of `index` in `table`, `None` when the reader holds no table.
105#[must_use]
106pub fn read<S: AsRef<str>>(table: Option<&[S]>, index: Index) -> Word<'_> {
107    match index {
108        Index::OutOfRange => Word::OutOfRange,
109        Index::At(i) => table
110            .and_then(|t| t.get(usize::from(i)))
111            .map_or(Word::Number(i), |w| Word::Entry(w.as_ref())),
112    }
113}
114
115/// The index a writer gives `word`: its first place in `table`, where
116/// that is at most `max`, and `out_of_range` for a word the table does not
117/// hold there, whose text stays in the writer's log.
118#[must_use]
119pub fn write<S: AsRef<str>>(table: &[S], word: &str, max: u8) -> Index {
120    table
121        .iter()
122        .position(|w| w.as_ref() == word)
123        .map_or(Index::OutOfRange, |i| Index::at(i, max))
124}
125
126/// An annotation's value read as a table: a list of at most `max`
127/// strings, each one `entry` accepts, and none twice where `once`. `None`
128/// for any other value, which is no table.
129#[must_use]
130pub fn list(
131    v: &Value,
132    max: usize,
133    entry: impl Fn(&str) -> bool,
134    once: bool,
135) -> Option<Vec<String>> {
136    let a = v.as_array()?;
137    if a.len() > max {
138        return None;
139    }
140    let mut out: Vec<String> = Vec::with_capacity(a.len());
141    for x in a {
142        let x = x.as_str()?;
143        if !entry(x) || (once && out.iter().any(|seen| seen == x)) {
144            return None;
145        }
146        out.push(x.to_owned());
147    }
148    Some(out)
149}
150
151/// An instance's table (`health.v2` §2.10, `alarms.v2` §4): the one table
152/// among the contracts it implements, the revisions its descriptor names.
153#[derive(Debug, Clone, PartialEq, Eq)]
154pub enum Instance<T> {
155    /// No named revision in hand holds one.
156    None,
157    /// The one list they hold.
158    Table(Vec<T>),
159    /// Two hold two different lists: no table.
160    Differ,
161}
162
163impl<T> Instance<T> {
164    /// The table, where the instance has one.
165    #[must_use]
166    pub fn table(&self) -> Option<&[T]> {
167        match self {
168            Instance::Table(t) => Some(t),
169            Instance::None | Instance::Differ => None,
170        }
171    }
172}
173
174/// An instance's table, from the table of each revision its descriptor
175/// names that the reader holds (`None`: that revision holds none, or its
176/// declaration is invalid). Never a revision the descriptor does not
177/// name: a table read under the wrong revision gives wrong words.
178#[must_use]
179pub fn instance_table<'a, T: PartialEq + Clone + 'a>(
180    named: impl IntoIterator<Item = Option<&'a [T]>>,
181) -> Instance<T> {
182    let mut held: Option<&[T]> = None;
183    for table in named.into_iter().flatten() {
184        match held {
185            None => held = Some(table),
186            Some(first) if first == table => {}
187            Some(_) => return Instance::Differ,
188        }
189    }
190    held.map_or(Instance::None, |t| Instance::Table(t.to_vec()))
191}
192
193/// One finding of a profile's lint of a contract's tables and
194/// declarations: what a build and `zk2 contract lint` report as an error.
195#[derive(Debug, Clone, PartialEq, Eq)]
196pub struct Lint {
197    /// The profile whose rule the finding is under, as `uses` lists it.
198    pub profile: &'static str,
199    /// The resource whose declaration drew it ([`Lint::place`]).
200    pub at: String,
201    /// The annotation key the finding is of, where it is of one key.
202    pub key: Option<&'static str>,
203    /// The reason's token, as the profile's fixtures spell it.
204    pub token: &'static str,
205    /// The reason in words.
206    pub says: &'static str,
207}
208
209impl Lint {
210    /// How a finding names a resource: its kind token and its template.
211    #[must_use]
212    pub fn place(r: &Resource) -> String {
213        format!("{}/{}", r.token, r.template.as_str())
214    }
215}
216
217impl std::fmt::Display for Lint {
218    /// A linter's line: `error[<profile> <token>] <at>: [<key>: ]<says>`.
219    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
220        write!(f, "error[{} {}] {}: ", self.profile, self.token, self.at)?;
221        if let Some(key) = self.key {
222            write!(f, "{key}: ")?;
223        }
224        f.write_str(self.says)
225    }
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231
232    #[test]
233    fn an_index_reads_as_its_entry_its_number_or_out_of_range() {
234        let table = ["a".to_owned(), "b".to_owned()];
235        assert_eq!(read(Some(&table[..]), Index::At(1)), Word::Entry("b"));
236        assert_eq!(read(Some(&table[..]), Index::At(2)), Word::Number(2));
237        assert_eq!(read::<String>(None, Index::At(0)), Word::Number(0));
238        assert_eq!(read(Some(&table[..]), Index::OutOfRange), Word::OutOfRange);
239        assert_eq!(write(&table, "b", 254), Index::At(1));
240        assert_eq!(write(&table, "b", 0), Index::OutOfRange, "past the code");
241        assert_eq!(write(&table, "c", 254), Index::OutOfRange);
242        assert_eq!(Index::at(255, 254), Index::OutOfRange);
243        for i in [Index::At(7), Index::OutOfRange] {
244            assert_eq!(Index::of_json(&i.to_json()), Ok(i));
245        }
246        assert_eq!(Index::of_json(&json!(256)), Err(WriteRefusal::Range));
247        assert_eq!(Index::of_json(&json!("x")), Err(WriteRefusal::Value));
248    }
249
250    #[test]
251    fn an_instance_has_the_one_table_its_named_revisions_hold() {
252        let (a, b) = (vec![1, 2], vec![1, 3]);
253        assert_eq!(instance_table::<u8>([None, None]), Instance::None);
254        assert_eq!(
255            instance_table([Some(&a[..]), None, Some(&a[..])]),
256            Instance::Table(a.clone())
257        );
258        assert_eq!(
259            instance_table([Some(&a[..]), Some(&b[..])]),
260            Instance::Differ
261        );
262        assert_eq!(Instance::<u8>::Differ.table(), None);
263        assert_eq!(Instance::Table(a.clone()).table(), Some(&a[..]));
264    }
265
266    #[test]
267    fn a_list_is_a_table_within_its_bound_and_its_entries_rule() {
268        let v = json!(["a", "b", "a"]);
269        assert_eq!(list(&v, 3, |_| true, false).map(|t| t.len()), Some(3));
270        assert_eq!(list(&v, 3, |_| true, true), None, "one twice");
271        assert_eq!(list(&v, 2, |_| true, false), None, "one too many");
272        assert_eq!(list(&v, 3, |s| s != "b", false), None);
273        assert_eq!(list(&json!(["a", 1]), 3, |_| true, false), None);
274        assert_eq!(list(&json!("a"), 3, |_| true, false), None);
275    }
276}