exchange-hours 1.2.2

Exchange trading hours, session boundaries, and calendar-aware bar boundaries. UTC in, UTC out.
Documentation
// SPDX-License-Identifier: MIT-0

//! The constant-evaluation fences behind the `holidays!` macro.
//!
//! Every invariant a holiday table relies on at runtime — a total order for
//! the partition-point gate and the binary-search lookup, rows inside the
//! published coverage window, a named artifact at an admissible tier, and
//! instants inside the `DayPolicy` ranges — is asserted during constant
//! evaluation, so a violation is a build failure rather than a wrong answer.
//! This copies the idiom `revisions!` established for schedule timelines.
use chrono::NaiveDate;

use super::{EvidenceTier, HolidayKind, HolidayRow, HolidayWindow};
use crate::calendar::exceptions::{BlockViolation, ExceptionBlock, first_block_violation};

/// The upper bound of a venue-local seconds-since-midnight close.
///
/// `86_400` is the end-exclusive close of a complete local day and is a legal
/// early close; the matching open bound is one second lower, exactly as
/// [`StaticDayPolicy`](crate::StaticDayPolicy) validates a caller's records.
const SECONDS_PER_DAY: u32 = 86_400;

/// Builds a hard-coded holiday trade date during constant evaluation.
#[expect(
    clippy::panic,
    reason = "const-eval only: an invalid sourced date must fail the build"
)]
pub(crate) const fn holiday_date(year: i32, month: u32, day: u32) -> NaiveDate {
    match NaiveDate::from_ymd_opt(year, month, day) {
        Some(date) => date,
        None => panic!("invalid hard-coded holiday trade date"),
    }
}

/// Orders `(year, month, day)` as one comparable scalar for constant
/// evaluation; tuple `PartialOrd` is not const-callable.
///
/// For a triple that is a real calendar date the scalar orders exactly as the
/// date does, which is why
/// [`HolidayWindow::new`](super::table::HolidayWindow::new)
/// stores one beside each validated endpoint: the fences below order windows
/// by these keys instead of comparing `NaiveDate` values they cannot.
pub(crate) const fn day_key(date: (i32, u32, u32)) -> i64 {
    date.0 as i64 * 10_000 + date.1 as i64 * 100 + date.2 as i64
}

/// Fails the build unless every `holidays!` invariant holds.
///
/// `dates` carries the same trade dates as `rows`, in the same order, as raw
/// `(year, month, day)` triples: `NaiveDate`'s comparison operators are not
/// const-callable, so ordering is decided on [`day_key`] scalars instead.
///
/// `windows` is the table's coverage, one inclusive span per audited era. Each
/// endpoint was already resolved to a real date by
/// [`HolidayWindow::new`](super::table::HolidayWindow::new) when the array was
/// built, so this fence only has to check the windows ordered and
/// non-overlapping, and that every row falls inside one of them, because a row
/// outside every window would be a date the table answers for while claiming
/// not to have audited it.
pub(crate) const fn assert_table(
    windows: &[HolidayWindow],
    dates: &[(i32, u32, u32)],
    rows: &[HolidayRow],
) {
    assert!(
        !windows.is_empty(),
        "a holiday table must declare at least one coverage window"
    );
    assert!(
        dates.len() == rows.len(),
        "holiday fence received a different number of trade dates than rows"
    );
    assert_ordered_windows(windows);

    let mut index = 0;
    while index < dates.len() {
        if index > 0 {
            assert!(
                day_key(dates[index]) > day_key(dates[index - 1]),
                "holiday table is not strictly ascending by trade date; \
                 a row is out of order or shadowed by a duplicate"
            );
        }
        assert!(
            in_windows(windows, dates[index]),
            "holiday row falls outside every coverage window its table declares"
        );
        assert!(
            !rows[index].document.as_str().is_empty(),
            "holiday row carries no document id"
        );
        assert!(
            matches!(rows[index].tier, EvidenceTier::T1 | EvidenceTier::T2),
            "holiday row is sourced below T2; LAW-PRIMARY-SOURCES admits only the \
             operator's own statement or the operator's own machine channel"
        );
        assert_instants(rows[index].kind);
        index += 1;
    }
}

/// The earliest `first` among a table's coverage windows.
pub(crate) const fn window_first(windows: &[HolidayWindow]) -> NaiveDate {
    assert!(
        !windows.is_empty(),
        "a holiday table must declare at least one coverage window"
    );
    let mut best = windows[0];
    let mut index = 1;
    while index < windows.len() {
        let candidate = windows[index];
        if candidate.first_key() < best.first_key() {
            best = candidate;
        }
        index += 1;
    }
    best.first()
}

/// The latest `last` among a table's coverage windows.
pub(crate) const fn window_last(windows: &[HolidayWindow]) -> NaiveDate {
    assert!(
        !windows.is_empty(),
        "a holiday table must declare at least one coverage window"
    );
    let mut best = windows[0];
    let mut index = 1;
    while index < windows.len() {
        let candidate = windows[index];
        if candidate.last_key() > best.last_key() {
            best = candidate;
        }
        index += 1;
    }
    best.last()
}

/// Fails the build unless the coverage windows ascend without overlapping.
///
/// Both endpoints of **every** window were validated when the array was built —
/// [`HolidayWindow::new`](super::table::HolidayWindow::new) runs once per
/// element, not only for the outermost pair — so the comparisons here are
/// between the stored keys of real dates.
const fn assert_ordered_windows(windows: &[HolidayWindow]) {
    let mut index = 0;
    while index < windows.len() {
        let window = windows[index];
        assert!(
            window.first_key() <= window.last_key(),
            "a holiday coverage window is inverted: its last date precedes its first"
        );
        if index > 0 {
            let previous = windows[index - 1];
            assert!(
                previous.last_key() < window.first_key(),
                "holiday coverage windows overlap or are out of order; a table \
                 ships one window per audited era, ascending"
            );
        }
        index += 1;
    }
}

/// Whether one raw date triple lies inside any coverage window.
///
/// The endpoints were validated when each window was constructed, so the
/// comparisons here are between the stored keys of real dates.
const fn in_windows(windows: &[HolidayWindow], date: (i32, u32, u32)) -> bool {
    let key = day_key(date);
    let mut index = 0;
    while index < windows.len() {
        let window = windows[index];
        if window.first_key() <= key && key <= window.last_key() {
            return true;
        }
        index += 1;
    }
    false
}

/// Fails the build when a row's instants leave the `DayPolicy` ranges.
///
/// A replacement row states no scalar instant of its own, so its complete block
/// set is handed to [`assert_blocks`] instead; every other kind is checked here.
///
/// The numeric order of an open and a close on one row is deliberately **not**
/// constrained: a wrapped trading day can open on the preceding local date at a
/// numerically later wall clock than its final close on the trade date, which
/// is exactly what
/// [`DayOverride::late_open_and_early_close`](crate::DayOverride::late_open_and_early_close)
/// documents for a caller's own records.
const fn assert_instants(kind: HolidayKind) {
    let (open_ssm, close_ssm) = match kind {
        HolidayKind::Closed | HolidayKind::Unsourced => return,
        HolidayKind::EarlyClose { close_ssm } => (0, close_ssm),
        HolidayKind::LateOpen { open_ssm } => (open_ssm, 0),
        HolidayKind::LateOpenAndEarlyClose {
            open_ssm,
            close_ssm,
        } => (open_ssm, close_ssm),
        // A replacement row states its instants block by block, so the whole
        // set is validated here and the scalars below do not apply to it. The
        // rule this arm exists for is the last one: a block set is the only
        // kind that can state an instant on a day other than its trade date.
        HolidayKind::ReplacementBlocks(set) => {
            assert_blocks(set);
            return;
        }
    };
    assert!(
        open_ssm < SECONDS_PER_DAY,
        "holiday row's late open is outside 0..86_400"
    );
    assert!(
        close_ssm <= SECONDS_PER_DAY,
        "holiday row's early close is outside 0..=86_400"
    );
}

/// Constructs [`HolidayKind::EarlyClose`], for a terse table row.
pub(crate) const fn early_close(close_ssm: u32) -> HolidayKind {
    HolidayKind::EarlyClose { close_ssm }
}

/// Constructs [`HolidayKind::LateOpen`], for a terse table row.
pub(crate) const fn late_open(open_ssm: u32) -> HolidayKind {
    HolidayKind::LateOpen { open_ssm }
}

/// Constructs [`HolidayKind::LateOpenAndEarlyClose`], for a terse table row.
pub(crate) const fn late_open_and_early_close(open_ssm: u32, close_ssm: u32) -> HolidayKind {
    HolidayKind::LateOpenAndEarlyClose {
        open_ssm,
        close_ssm,
    }
}

/// Whether any row of a table states a replacement block set.
///
/// Resolved during constant evaluation so the query hot path reads one bit
/// instead of walking the table: a table that ships no block row must not pay
/// for the replacement scan, and the scan must not be reachable for it.
pub(crate) const fn any_blocks(rows: &[HolidayRow]) -> bool {
    let mut index = 0;
    while index < rows.len() {
        if matches!(rows[index].kind, HolidayKind::ReplacementBlocks(_)) {
            return true;
        }
        index += 1;
    }
    false
}

/// Fails the build unless a row's replacement block set is well formed.
///
/// The rules are **not** restated here. They live in one place,
/// [`first_block_violation`], which a caller's
/// [`StaticSessionExceptions::new`](crate::StaticSessionExceptions::new) applies
/// to its own records — so a built-in row and a caller's record are held to the
/// same shape by construction, and the public tests that fence a caller's
/// rejected records fence the built-in rows' rules too. This function only
/// chooses what a violation means here: a build failure rather than a returned
/// error.
///
/// **This is live rather than aspirational.** [`assert_table`] calls
/// [`assert_instants`] for every row, and that calls this function for the one
/// kind that states instants of its own; the call chain is `holidays!` →
/// `assert_table` → `assert_instants` → `assert_blocks`, so a malformed block
/// set fails the build of the module that declares it. Stage 3 shipped the path
/// with no block row to exercise it, so
/// `tests/session_exceptions.rs::malformed_block_sets_are_rejected_with_a_named_violation`
/// pins the rules and their reporting order through the caller's identical
/// predicate, and `assert_table`'s own call remains the only path a built-in row
/// takes.
///
/// Each variant gets its own literal message, because a `panic!` in constant
/// evaluation cannot format, and the message is the whole diagnostic a reader
/// gets from a failed build.
#[expect(
    clippy::panic,
    reason = "const-eval only: a malformed built-in replacement row must fail the build"
)]
const fn assert_blocks(set: &[ExceptionBlock]) {
    match first_block_violation(set) {
        None => {}
        Some(BlockViolation::Empty) => panic!(
            "holiday replacement row carries an empty block set; a trade date with no \
             blocks is HolidayKind::Closed"
        ),
        Some(BlockViolation::OffsetOutOfRange { .. }) => {
            panic!("holiday replacement block's opening day offset is outside the block day range")
        }
        Some(BlockViolation::OpenOutOfRange { .. }) => {
            panic!("holiday replacement block's open is outside 0..86_400")
        }
        Some(BlockViolation::CloseOutOfRange { .. }) => {
            panic!("holiday replacement block's close is outside 0..=86_400")
        }
        Some(BlockViolation::ClosesAfterTradeDate { .. }) => panic!(
            "holiday replacement block opens on its own trade date and closes after it; \
             a trade date is the local date of its final close"
        ),
        Some(BlockViolation::NotOrdered { .. }) => {
            panic!("holiday replacement blocks are not ordered by opening day and open time")
        }
    }
}