Skip to main content

flow_types/
names.rs

1//! How decoding finds a name a declaration declares from the name the JSON
2//! writes (`stdlib.md`, *`json`*): each declaration's field and
3//! constructor names, indexed once by their key under a [`Spelling`], so
4//! reading a member's name is one lookup however many values are read.
5
6use std::borrow::Cow;
7use std::collections::HashMap;
8
9use crate::shape::{Constructor, Payload};
10use crate::types::Body;
11
12/// How a name the JSON writes is compared with the names a type declares.
13#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
14pub enum Spelling {
15    /// As written: a name is its own key.
16    Exact,
17    /// By the relaxed key: the name with every `_` and `-` removed and
18    /// every ASCII letter lowercased, so `isDraft`, `IS_DRAFT`,
19    /// `is-draft` and `is_draft` share the key `isdraft`.
20    Relaxed,
21}
22
23impl Spelling {
24    /// The key `name` is found by.
25    pub fn key(self, name: &str) -> Cow<'_, str> {
26        match self {
27            Spelling::Exact => Cow::Borrowed(name),
28            Spelling::Relaxed => Cow::Owned(
29                name.chars()
30                    .filter(|c| !matches!(c, '_' | '-'))
31                    .map(|c| c.to_ascii_lowercase())
32                    .collect(),
33            ),
34        }
35    }
36}
37
38/// A declaration's names by their key under one [`Spelling`]: a record's
39/// fields, or an enum's constructors and each constructor's named payload
40/// fields, each mapped to its position in declaration order.
41#[derive(Clone, Debug)]
42pub struct NameIndex {
43    spelling: Spelling,
44    members: Keys,
45    payloads: Vec<Keys>,
46}
47
48type Keys = HashMap<Box<str>, usize>;
49
50/// Two names one scope of a declaration declares that share a key.
51#[derive(Clone, PartialEq, Eq, Debug)]
52pub struct SharedKey {
53    /// The name declared first.
54    pub first: String,
55    /// The name declared after it.
56    pub second: String,
57    /// The key both have.
58    pub key: String,
59}
60
61impl NameIndex {
62    /// Indexes the names `body` declares by their key under `spelling`.
63    ///
64    /// # Errors
65    ///
66    /// The first two names of one scope that share a key, scopes taken in
67    /// order: the record's fields, or the enum's constructors and then each
68    /// constructor's payload fields.
69    pub fn of(body: &Body, spelling: Spelling) -> Result<NameIndex, SharedKey> {
70        let index = |names: Vec<&str>| -> Result<Keys, SharedKey> {
71            let mut keys = Keys::with_capacity(names.len());
72            for (at, name) in names.iter().enumerate() {
73                let key = spelling.key(name);
74                if let Some(&first) = keys.get(&*key) {
75                    return Err(SharedKey {
76                        first: names[first].to_owned(),
77                        second: (*name).to_owned(),
78                        key: key.into_owned(),
79                    });
80                }
81                keys.insert(key.into(), at);
82            }
83            Ok(keys)
84        };
85        let (members, payloads) = match body {
86            Body::Record(shape, _) => (index(shape.fields().collect())?, Vec::new()),
87            Body::Enum(shape, _) => {
88                let ctors = shape.constructors();
89                let members = index(ctors.iter().map(Constructor::name).collect())?;
90                let payloads = ctors
91                    .iter()
92                    .map(|ctor| match ctor.payload() {
93                        Payload::Named(fields) => {
94                            index(fields.iter().map(|field| &**field).collect())
95                        }
96                        Payload::None | Payload::Positional(_) => Ok(Keys::new()),
97                    })
98                    .collect::<Result<_, _>>()?;
99                (members, payloads)
100            }
101            Body::Newtype(_) | Body::Host | Body::NonData => (Keys::new(), Vec::new()),
102        };
103        Ok(NameIndex {
104            spelling,
105            members,
106            payloads,
107        })
108    }
109
110    /// The position of the record field or enum constructor `written` names.
111    pub fn member(&self, written: &str) -> Option<usize> {
112        self.members.get(&*self.spelling.key(written)).copied()
113    }
114
115    /// The position of the field `written` names in the named payload of the
116    /// constructor at `ctor`.
117    pub fn payload_field(&self, ctor: usize, written: &str) -> Option<usize> {
118        self.payloads
119            .get(ctor)?
120            .get(&*self.spelling.key(written))
121            .copied()
122    }
123}