alpha2-model 0.10.0

Versioned project and timeline model for alpha2.
Documentation
//! Ids that name nothing: the close ids of the namespace, and the namespace an id belongs to.

use alpha2_diagnose::suggest::{self, Suggestion};
use alpha2_diagnose::write::quote;
use alpha2_diagnose::{Diagnostic, Edit, Fix, Node, Path};

use super::ids::Namespace;
use super::place::{Anchor, Locator};
use crate::{AudioNodeRef, BindingProblem, DataProblem, ModelError};

const LISTED: usize = 8;

enum Among<'a> {
    Namespace(Namespace),
    Nodes(&'a str),
    CaptionStyles(&'a str),
}

impl Among<'_> {
    const fn noun(&self) -> &'static str {
        match self {
            Self::Namespace(namespace) => namespace.noun(),
            Self::Nodes(_) => Namespace::Node.noun(),
            Self::CaptionStyles(_) => "caption style",
        }
    }
}

fn wanted<'a>(
    error: &'a ModelError,
    path: &Path,
    locator: &Locator<'_>,
) -> Option<(Among<'a>, String)> {
    use ModelError as E;
    let namespace = |namespace, id: &str| Some((Among::Namespace(namespace), id.to_owned()));
    match error {
        E::InvalidNodeSource { source, .. }
            if locator
                .index()
                .paths(Namespace::Source, source.as_str())
                .is_empty() =>
        {
            namespace(Namespace::Source, source.as_str())
        }
        E::UnknownClipSource { source, .. }
        | E::InvalidDataSet {
            problem: DataProblem::UnknownSource(source),
            ..
        } => namespace(Namespace::Source, source.as_str()),
        E::UnknownEffectResource { resource, .. }
        | E::UnknownNodeResource { resource, .. }
        | E::UnknownSourceResource { resource, .. } => {
            namespace(Namespace::EffectResource, resource.as_str())
        }
        E::UnknownComposition { composition, .. } => {
            namespace(Namespace::Composition, composition.as_str())
        }
        E::UnknownGroupComposition { target, .. } => {
            namespace(Namespace::Composition, target.as_str())
        }
        E::UnknownNodeInput {
            composition,
            target,
            ..
        } => Some((
            Among::Nodes(composition.as_str()),
            target.as_str().to_owned(),
        )),
        E::UnknownCompositionOutput { composition, node } => {
            Some((Among::Nodes(composition.as_str()), node.as_str().to_owned()))
        }
        E::UnknownAudioBus { bus, .. } => namespace(Namespace::Bus, bus.as_str()),
        E::UnknownAudioSidechain { sidechain, .. } => match sidechain {
            AudioNodeRef::Track(track) => namespace(Namespace::Track, track.as_str()),
            AudioNodeRef::Bus(bus) => namespace(Namespace::Bus, bus.as_str()),
        },
        E::UnknownCaptionStyle { track, name, .. } => {
            Some((Among::CaptionStyles(track.as_str()), name.clone()))
        }
        E::InvalidDataBinding {
            problem: BindingProblem::UnknownData,
            ..
        } => {
            let node = locator.tree().at(path)?;
            let id = node.as_str().or_else(|| node.get("data")?.as_str())?;
            namespace(Namespace::DataSet, id)
        }
        _ => None,
    }
}

fn candidates<'a>(among: &Among<'_>, locator: &'a Locator<'_>) -> Vec<&'a str> {
    match among {
        Among::Namespace(namespace) => locator.index().ids(*namespace),
        Among::Nodes(composition) => locator.index().node_ids(composition),
        Among::CaptionStyles(track) => locator
            .anchor_path(Anchor::Track(track))
            .and_then(|path| locator.tree().at(&path.key("captions").key("styles")))
            .and_then(Node::as_map)
            .map(|entries| entries.iter().map(|entry| entry.key.as_str()).collect())
            .unwrap_or_default(),
    }
}

fn written_at(tree: &Node, path: &Path, id: &str) -> Option<Path> {
    let node = tree.at(path)?;
    if node.as_str() == Some(id) {
        return Some(path.clone());
    }
    let entries = node.as_map()?;
    entries
        .iter()
        .find(|entry| entry.value.as_str() == Some(id))
        .map(|entry| path.key(entry.key.clone()))
}

pub fn advise(diagnostic: &mut Diagnostic, error: &ModelError, locator: &Locator<'_>) {
    let Some((among, id)) = wanted(error, &diagnostic.path, locator) else {
        return;
    };
    let noun = among.noun();
    let elsewhere: Vec<&str> = locator
        .index()
        .namespaces_of(&id)
        .into_iter()
        .filter(|namespace| !matches!(&among, Among::Namespace(own) if own == namespace))
        .map(Namespace::noun)
        .collect();
    if let Some(other) = elsewhere.first() {
        diagnostic.help.push(format!(
            "{} is the id of a {other}, not of a {noun}; ids of different kinds never refer to \
             each other",
            quote(&id)
        ));
    }
    let candidates = candidates(&among, locator);
    match suggest::closest(&id, candidates.iter().copied()) {
        Suggestion::One(close) => {
            diagnostic
                .help
                .push(format!("did you mean the {noun} {}?", quote(close)));
            if let Some(path) = written_at(locator.tree(), &diagnostic.path, &id) {
                diagnostic.fixes.push(Fix::likely(
                    format!("name the {noun} {}", quote(close)),
                    vec![Edit::Replace {
                        path,
                        value: Node::text(close),
                    }],
                ));
            }
        }
        Suggestion::Several(close) => diagnostic.help.push(format!(
            "close {noun} ids: {}",
            suggest::listed(close, LISTED)
        )),
        Suggestion::None if candidates.is_empty() => {
            diagnostic.help.push(format!("the document has no {noun}"));
        }
        Suggestion::None => diagnostic.help.push(format!(
            "the {noun} ids are {}",
            suggest::listed(candidates, LISTED)
        )),
    }
}