ingraph-derive 0.1.0

The attribute and derive macros for ingraph: the words a record, node, key, filter and vocabulary declaration is written in.
Documentation
//! The NEAR-MISS line a named refusal ends with — one reader, called from every position with THAT
//! position's own words.
//!
//! Every refusal in this crate already teaches: it names what the position takes and why. What it
//! did not do is answer the commonest mistake of all, which is not *I do not know this grammar* but
//! *I typed it wrong* — so `sortble` was told the whole element vocabulary and left to spot which
//! of the four it had nearly written.
//!
//! # It APPENDS, and that is the whole of the contract
//!
//! [`did_you_mean`] answers a CLAUSE, never a sentence. The teaching half is the position's and is
//! untouched: a suggestion is a second thing said about the same token, and a reader who typed a
//! word that is near nothing still gets exactly the sentence they got before. That is also what
//! makes the goldens legible — every re-blessing in this round is an ADDITION at the end of a line.
//!
//! # ONE engine, called with each position's vocabulary
//!
//! The alternative was a reader that ACCUMULATED the words a walk offered, which cannot drift by
//! construction. It is not what this is: a walk's `is_ident` chain would have to be rewritten
//! through an accumulator threaded beside the error sink, which is a control-flow change at every
//! position for a diagnostics round. The trade is stated rather than discovered — a hand-written
//! list can fall behind the sentence beside it — and the mitigation is that the list and the
//! sentence are written at the same call, so they are read together or not at all.
//!
//! # The vocabulary is what the SENTENCE names
//!
//! One rule decides every list in this crate: a position suggests the words its own teaching
//! sentence offers, and no others. A word the sentence refuses by name is not in it (an author who
//! writes that word gets the reasoned refusal, which is better than a suggestion), and a word from
//! a neighbouring scope is not in it either (suggesting it would send a reader to a position that
//! would refuse them again).
//!
//! # A Rust KEYWORD is an ordinary word here
//!
//! The comparison is over UNRAW'd spellings, so `r#type` is `type`. A grammar whose words reach
//! GraphQL and SQL has no reason to care which of them rustc reserves, and the one place the
//! escape shows is here: an author who wrote `r#type` at a position taking `type` wrote the word,
//! and is told so rather than being told nothing.

/// The clause a teaching sentence gains when the word written is a NEAR MISS of one it names.
///
/// The empty string where nothing is near enough, which is the common case and costs the sentence
/// nothing: a refusal is never made worse by this reader, only sometimes better.
///
/// `written` is compared UNRAW'd — see [`word`], which is how every caller reads an entry's name.
pub(crate) fn did_you_mean<S: AsRef<str>>(
  written: &str,
  vocabulary: impl IntoIterator<Item = S>,
) -> String {
  nearest(written, vocabulary)
    .map(|word| meant(&word))
    .unwrap_or_default()
}

/// The clause itself, over a word a refusal has ALREADY decided on.
///
/// The measured half and the ruled half spell one sentence: a position that corrects a WORD knows
/// its successor without measuring anything, and `rename` → `prefix` is the case that needs it —
/// five edits over six characters, so [`near`]'s cutoff offers nothing and the clause would
/// otherwise be written out a second time beside this one.
pub(crate) fn meant(word: &str) -> String {
  format!(" — did you mean `{word}`?")
}

/// The vocabulary's own word nearest to what was written, where one is near ENOUGH to name.
///
/// The FIRST of the closest, so a tie is broken by the order the position lists its words in — a
/// deterministic answer rather than whichever the iterator happened to reach last.
fn nearest<S: AsRef<str>>(
  written: &str,
  vocabulary: impl IntoIterator<Item = S>,
) -> Option<String> {
  let written: Vec<char> = unraw(written).chars().collect();
  let mut best: Option<(usize, String)> = None;
  for candidate in vocabulary {
    let candidate = candidate.as_ref();
    let Some(distance) = near(&written, candidate) else {
      continue;
    };
    if best.as_ref().is_none_or(|(closest, _)| distance < *closest) {
      best = Some((distance, candidate.to_owned()));
    }
  }
  best.map(|(_, word)| word)
}

/// How far `candidate` is from what was written, where that is near enough to be a typo of it.
///
/// # The cutoff, and why it is two rules rather than one
///
/// A flat edit-distance ceiling is wrong at both ends of a vocabulary this shape. At two edits
/// every three-letter word is a near miss of every other one — `ask`, `key`, `set`, `out` are
/// mutually within two — so a bare ceiling would answer a reader who wrote `own` with a word they
/// were not writing. A flat RATIO is wrong the other way: half of a twelve-letter word is six
/// edits, which is not a typo of anything.
///
/// So both hold. At most [`CEILING`] edits, AND at least half the written word survives them —
/// which admits one edit at three characters, two at four, and two at every length above.
///
/// MEASURED rather than assumed, and the measurement is a test: `the_cutoff_keeps_every_shipped_
/// vocabulary_apart` runs every word of the framework's eight closed tables and of the three widest
/// hand-written positions against its own neighbours, and none of them is a near miss of another.
/// That is the property the cutoff has to have — a legal word that looked like a typo of its
/// neighbour would send every author who spelled it right towards the wrong one.
///
/// Zero is a distance like any other, and it is reachable: the comparison is unraw'd, so an author
/// who wrote `r#type` where the position takes `type` lands here exactly.
fn near(written: &[char], candidate: &str) -> Option<usize> {
  let distance = distance(written, candidate);
  (distance <= CEILING && distance.saturating_mul(2) <= written.len()).then_some(distance)
}

/// The most edits a typo is allowed to be.
const CEILING: usize = 2;

/// The Levenshtein distance between the two, over CHARACTERS.
///
/// Two rows rather than a full matrix, the previous one being all the next depends on. Characters
/// rather than bytes because a vocabulary word is ASCII but what an author typed is not necessarily
/// — a multi-byte character counts as the one edit it is rather than as its encoding's length.
fn distance(written: &[char], candidate: &str) -> usize {
  let candidate: Vec<char> = candidate.chars().collect();
  if written.is_empty() {
    return candidate.len();
  }
  let mut previous: Vec<usize> = (0..=written.len()).collect();
  let mut current: Vec<usize> = vec![0; written.len() + 1];
  for (row, theirs) in candidate.iter().enumerate() {
    current[0] = row + 1;
    for (column, ours) in written.iter().enumerate() {
      let substitution = previous[column] + usize::from(ours != theirs);
      current[column + 1] = substitution
        .min(previous[column + 1] + 1)
        .min(current[column] + 1);
    }
    core::mem::swap(&mut previous, &mut current);
  }
  previous[written.len()]
}

/// The word an entry WROTE, as a vocabulary spells one — or nothing, where the entry named no
/// single word.
///
/// A path with several segments names nothing this reader could be near, and neither does an entry
/// whose name is not an identifier at all: both fall through to the position's own sentence, which
/// is already about the shape rather than about the spelling.
pub(crate) fn word(path: &syn::Path) -> Option<String> {
  path.get_ident().map(|ident| unraw(&ident.to_string()))
}

/// A spelling with Rust's raw escape taken off, `r#type` being the word `type`.
fn unraw(word: &str) -> String {
  word.strip_prefix("r#").unwrap_or(word).to_owned()
}

#[cfg(test)]
mod tests;