flow-types 0.1.0-rc.5

The Flow declaration model with no values: types, declarations and their identities, record and enum shapes, and which types decoding may build.
Documentation
//! How decoding finds a name a declaration declares from the name the JSON
//! writes (`stdlib.md`, *`json`*): each declaration's field and
//! constructor names, indexed once by their key under a [`Spelling`], so
//! reading a member's name is one lookup however many values are read.

use std::borrow::Cow;
use std::collections::HashMap;

use crate::shape::{Constructor, Payload};
use crate::types::Body;

/// How a name the JSON writes is compared with the names a type declares.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum Spelling {
    /// As written: a name is its own key.
    Exact,
    /// By the relaxed key: the name with every `_` and `-` removed and
    /// every ASCII letter lowercased, so `isDraft`, `IS_DRAFT`,
    /// `is-draft` and `is_draft` share the key `isdraft`.
    Relaxed,
}

impl Spelling {
    /// The key `name` is found by.
    pub fn key(self, name: &str) -> Cow<'_, str> {
        match self {
            Spelling::Exact => Cow::Borrowed(name),
            Spelling::Relaxed => Cow::Owned(
                name.chars()
                    .filter(|c| !matches!(c, '_' | '-'))
                    .map(|c| c.to_ascii_lowercase())
                    .collect(),
            ),
        }
    }
}

/// A declaration's names by their key under one [`Spelling`]: a record's
/// fields, or an enum's constructors and each constructor's named payload
/// fields, each mapped to its position in declaration order.
#[derive(Clone, Debug)]
pub struct NameIndex {
    spelling: Spelling,
    members: Keys,
    payloads: Vec<Keys>,
}

type Keys = HashMap<Box<str>, usize>;

/// Two names one scope of a declaration declares that share a key.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct SharedKey {
    /// The name declared first.
    pub first: String,
    /// The name declared after it.
    pub second: String,
    /// The key both have.
    pub key: String,
}

impl NameIndex {
    /// Indexes the names `body` declares by their key under `spelling`.
    ///
    /// # Errors
    ///
    /// The first two names of one scope that share a key, scopes taken in
    /// order: the record's fields, or the enum's constructors and then each
    /// constructor's payload fields.
    pub fn of(body: &Body, spelling: Spelling) -> Result<NameIndex, SharedKey> {
        let index = |names: Vec<&str>| -> Result<Keys, SharedKey> {
            let mut keys = Keys::with_capacity(names.len());
            for (at, name) in names.iter().enumerate() {
                let key = spelling.key(name);
                if let Some(&first) = keys.get(&*key) {
                    return Err(SharedKey {
                        first: names[first].to_owned(),
                        second: (*name).to_owned(),
                        key: key.into_owned(),
                    });
                }
                keys.insert(key.into(), at);
            }
            Ok(keys)
        };
        let (members, payloads) = match body {
            Body::Record(shape, _) => (index(shape.fields().collect())?, Vec::new()),
            Body::Enum(shape, _) => {
                let ctors = shape.constructors();
                let members = index(ctors.iter().map(Constructor::name).collect())?;
                let payloads = ctors
                    .iter()
                    .map(|ctor| match ctor.payload() {
                        Payload::Named(fields) => {
                            index(fields.iter().map(|field| &**field).collect())
                        }
                        Payload::None | Payload::Positional(_) => Ok(Keys::new()),
                    })
                    .collect::<Result<_, _>>()?;
                (members, payloads)
            }
            Body::Newtype(_) | Body::Host | Body::NonData => (Keys::new(), Vec::new()),
        };
        Ok(NameIndex {
            spelling,
            members,
            payloads,
        })
    }

    /// The position of the record field or enum constructor `written` names.
    pub fn member(&self, written: &str) -> Option<usize> {
        self.members.get(&*self.spelling.key(written)).copied()
    }

    /// The position of the field `written` names in the named payload of the
    /// constructor at `ctor`.
    pub fn payload_field(&self, ctor: usize, written: &str) -> Option<usize> {
        self.payloads
            .get(ctor)?
            .get(&*self.spelling.key(written))
            .copied()
    }
}