use std::ffi::OsString;
use std::fmt;
use crumbkit::{Document, Failure, Prose, Recovery};
use schemars::JsonSchema;
use serde::Serialize;
use starmap::{Declaration, Mode, Name};
use crate::cli::CheckArgs;
use crate::codes::{FAMILY_UNDECLARED, VARIABLE_UNDECLARED};
use crate::mode;
use crate::scan::{self, Dirs};
use crate::spec;
pub(crate) const CHECK: Document<Prose<Checked, Undeclared>> = Document::new(
"starmap",
"check",
1,
"A spec that follows every rule of the file: its path, digest, number of variables, the reads in src and the mode.",
);
#[derive(Debug, Serialize, JsonSchema)]
pub(crate) struct Checked {
spec: String,
digest: String,
variables: u64,
read: u64,
undeclared: Vec<String>,
checks_without_sentence: Vec<String>,
sentences_without_check: Vec<String>,
unresolved: Vec<String>,
#[serde(skip)]
src: String,
#[serde(skip)]
src_verb: &'static str,
#[serde(skip)]
scanned_nothing: bool,
mode: ModeWord,
}
#[derive(Debug, Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub(crate) enum ModeWord {
Local,
Production,
}
impl From<Mode> for ModeWord {
fn from(mode: Mode) -> Self {
match mode {
Mode::Local => Self::Local,
Mode::Production => Self::Production,
}
}
}
impl fmt::Display for Checked {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let (declared, read) = (self.variables, self.read);
let noun = if declared == 1 {
"variable"
} else {
"variables"
};
if self.scanned_nothing {
return write!(
formatter,
"{} declares {declared} {noun}, and no source directory is scanned.",
self.spec
);
}
let reads = match read {
1 if declared == 1 => "it".to_owned(),
0 => "none of them".to_owned(),
_ if read == declared => format!("all {read}"),
_ => format!("{read} of them"),
};
write!(
formatter,
"{} declares {declared} {noun}, and {} {} {reads}.",
self.spec, self.src, self.src_verb
)?;
match self.unresolved.split_last() {
None => Ok(()),
Some((last, [])) => write!(formatter, " check cannot resolve the name read at {last}."),
Some((last, rest)) => write!(
formatter,
" check cannot resolve the names read at {} and {last}.",
rest.join(", ")
),
}
}
}
#[derive(Debug, Failure)]
pub(crate) enum Undeclared {
#[failure(
code = VARIABLE_UNDECLARED,
hint = "declare {name} in {file}",
alternative = Recovery::Hint(format!("stop reading {name}")),
field(name = name.as_str()),
field(at = at.as_str()),
)]
Variable {
name: Name,
at: String,
file: String,
},
#[failure(
code = FAMILY_UNDECLARED,
hint = "declare [families.{prefix}] in {file}",
alternative = Recovery::Hint("read a declared name".to_owned()),
field(prefix = prefix.as_str()),
field(at = at.as_str()),
)]
Family {
prefix: Name,
at: String,
file: String,
},
}
impl fmt::Display for Undeclared {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Variable { name, at, file } => {
write!(
formatter,
"{at} reads {name}, which {file} does not declare"
)
}
Self::Family { prefix, at, file } => write!(
formatter,
"{at} reads names that start with {prefix}_, and {file} declares no family {prefix}"
),
}
}
}
impl std::error::Error for Undeclared {}
pub(crate) fn check(
args: &CheckArgs,
vars: Vec<(OsString, OsString)>,
) -> Result<Prose<Checked, Undeclared>, crumbkit::Error> {
let spec::Opened { spec, located } = spec::open(&args.file.spec)?;
let file = located.file.display().to_string();
let scan::Scanned {
reads,
checks,
families,
unresolved,
} = scan::scan_all(&located.src)?;
let bindings = starmap::capture(&spec, vars);
let (mode, note) = mode::decide(&spec, &bindings);
let src = Dirs(&located.src);
let mut notes = vec![note];
let mut checks_without_sentence = Vec::new();
for (name, at) in &checks {
if spec
.variable(name)
.is_some_and(|variable| variable.check().is_none())
{
notes.push(format!(
"{at} checks {name} in code, and {file} states no check sentence for it."
));
checks_without_sentence.push(name.to_string());
}
}
let mut sentences_without_check = Vec::new();
if !src.is_empty() {
for (name, _) in spec
.variables()
.filter(|(name, variable)| variable.check().is_some() && !checks.contains_key(*name))
{
notes.push(format!(
"{file} states a check sentence for {name}, and no field in {src} names a check for it."
));
sentences_without_check.push(name.to_string());
}
}
let mut read = 0;
let mut undeclared = Vec::new();
let mut undeclared_names = Vec::new();
for (name, places) in reads {
let member = matches!(
spec.declared(&name),
Some(Declaration::Member { family, key }) if family.lists(key)
);
if spec.variable(&name).is_some() {
read += 1;
} else if !member {
let at = places.into_iter().next().unwrap_or_default();
undeclared_names.push(name.to_string());
undeclared.push(Undeclared::Variable {
name,
at,
file: file.clone(),
});
}
}
for (prefix, places) in families {
if spec.family(&prefix).is_none() {
let at = places.into_iter().next().unwrap_or_default();
undeclared.push(Undeclared::Family {
prefix,
at,
file: file.clone(),
});
}
}
let checked = Checked {
digest: spec.digest().to_string(),
variables: u64::try_from(spec.variables().count()).unwrap_or(u64::MAX),
read,
undeclared: undeclared_names,
checks_without_sentence,
sentences_without_check,
unresolved,
src: Dirs(&located.src).to_string(),
src_verb: Dirs(&located.src).verb("reads", "read"),
scanned_nothing: Dirs(&located.src).is_empty(),
spec: file,
mode: mode.into(),
};
Ok(Prose::with_failures(checked, undeclared).note(notes.join("\n")))
}