ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! THE CRON SEAM, expansion side: is this a calendar expression, and is that a zone?
//!
//! # The seam exists because the implementation was temporary — and it has been replaced
//!
//! The ruling that put cron in v1 said what rides underneath it: a third-party crate FIRST, and the
//! user's own implementation later. The later has arrived. What changed is the crate the two
//! functions below call; what did not change is a single word an author writes or a single meaning a
//! schedule has — which is what the seam was built to make possible, and this swap is the
//! measurement that it did.
//!
//! There are TWO halves of the seam in the workspace, one per crate, because the build order forbids
//! one: `ingraph` cannot reach this crate (it expands through the derive, which is built on it), so
//! the runtime's own half lives in `ingraph::drive`. A swap touches both, and they are written to be
//! read together.
//!
//! # What is underneath, and what it costs
//!
//! **`cronp`** — `no_std`, `no_alloc`, and NO dependency at all in the configuration this asks for.
//! It parses into a bitset per field, takes its DIALECT as a type parameter, and refuses with a
//! [`ParseError`](cronp::ParseError) carrying a byte [`Span`](cronp::Span). The dialect is
//! [`Vixie`](cronp::Vixie), whose own constants are exactly the pins this framework had been
//! stating by hand: five fields, no seconds, no year, and dom/dow the classic
//! [`Union`](cronp::DomDowRule::Union).
//!
//! It EVALUATES nothing, which is the property this half wants most: an expansion-time check that
//! computed a next-due would be a check whose answer depended on the machine the build ran on. The
//! previous crate had to be told to fall back to UTC for exactly that reason; there is now nothing
//! to tell.
//!
//! # What this half checks, and what it deliberately does not
//!
//! The FIELDS, the EXPRESSION, and the zone's NAME. It does not compute a next-due and it must not:
//! the zone a schedule runs in is the one where the program RUNS, and expansion happens wherever the
//! build happens. The zone name is checked separately, and only where this machine HAS a database to
//! check it against.
//!
//! # The refusal quotes the expression under a caret
//!
//! The span is spent rather than the sentence alone. A reader is shown the text they wrote with the
//! offending run marked, which is what a compiler diagnostic does and what the previous crate's own
//! rendering happened to give — so the swap is a strict keep rather than a trade.

use cronp::{Schedule, Vixie};

/// How many fields a cron expression has here: the classic five — minute, hour, day of month,
/// month, day of week.
///
/// Checked HERE rather than left to the crate, and the reason survives the swap even though the
/// dialect now states it too: [`Vixie::MIN_FIELDS`](cronp::Dialect::MIN_FIELDS) is five and its
/// `MAX_FIELDS` is five as well, so the crate would refuse a sixth field on its own — but it would
/// refuse it as a PARSE error, and the useful sentence here is that a timezone is not a sixth field
/// because there is a word for it. One rule, said by the party that knows why.
pub const FIELDS: usize = 5;

/// Read `expression` as a calendar expression, and `zone` as an IANA name where one was written.
///
/// # Errors
///
/// The reason, ready to be quoted into a refusal by the front end that holds the span. A parse
/// refusal carries the expression with the offending run under a caret; the two rules this module
/// owns say themselves.
pub fn check(expression: &str, zone: Option<&str>) -> Result<(), String> {
  let written = expression.split_ascii_whitespace().count();
  if written != FIELDS {
    return Err(format!(
      "a cron expression here is the classic {FIELDS} fields — minute, hour, day of month, month, \
       day of week — and this one has {written}. A timezone is not a sixth field: it is the `tz = \
       \"<IANA>\"` word beside this one, or the system's zone where nothing said otherwise"
    ));
  }

  Schedule::<Vixie>::parse(expression).map_err(|refusal| caret(expression, &refusal))?;

  match zone {
    Some(zone) => zone_exists(zone),
    None => Ok(()),
  }
}

/// A parse refusal with the expression under it and a caret on the offending run.
///
/// Written out rather than taken from the crate, which reports the span and leaves the quoting to
/// whoever holds the text. Both halves of the seam render it the same way and neither can share the
/// other's copy — the build order again — so the two are kept identical by
/// `the_two_halves_render_one_caret`, one file over in `ingraph`.
///
/// The caret is at least one column wide, because an empty span is a real answer: a parser that ran
/// out of input points AT the end, and a marker with no width would point at nothing.
fn caret(expression: &str, refusal: &cronp::ParseError) -> String {
  let span = refusal.span();
  // BYTE offsets from the parser, COLUMNS on the page. They differ the moment an expression carries
  // a non-ASCII byte — which a garbage one may — so the pad is counted in characters over the text
  // actually printed rather than assumed equal to the offset.
  let start = expression
    .get(..span.start())
    .map_or(0, |before| before.chars().count());
  let width = expression
    .get(span.start()..span.end())
    .map_or(1, |marked| marked.chars().count().max(1));
  format!(
    "{refusal}\n  {expression}\n  {pad}{caret}",
    pad = " ".repeat(start),
    caret = "^".repeat(width),
  )
}

/// Whether `zone` is a name this machine's time zone database has.
///
/// A TYPO CHECK, and it is written to be one rather than a portability trap. A machine with no
/// database refuses NOTHING here: `America/New_York` is a valid declaration whether or not the
/// container that compiled it shipped a `zoneinfo`, and the runtime is where the zone is actually
/// needed. So the absence of a database is detected and the check stands down.
fn zone_exists(zone: &str) -> Result<(), String> {
  if jiff::tz::TimeZone::get(zone).is_ok() {
    return Ok(());
  }
  if jiff::tz::db().available().next().is_none() {
    return Ok(());
  }
  Err(format!(
    "`{zone}` is not a time zone this machine's database has — the word takes an IANA name, as in \
     `tz = \"America/New_York\"`"
  ))
}

#[cfg(test)]
mod tests;