Skip to main content

relate_core/temporal/
construct.rs

1//! Construction of temporal values from components and maps. The
2//! zone-resolution cluster lives in [`super::zone`] (ADR-0340), the
3//! truncation cluster in [`super::truncate`], and the CIP-223 pattern
4//! formatter in [`super::format`].
5
6use chrono::{
7    Datelike, Days, Duration as ChronoDur, NaiveDate, NaiveDateTime, NaiveTime, Timelike, Weekday,
8};
9
10use crate::{bare_type_name, Error, Result, Value};
11
12use super::clock::now_value;
13use super::clock::{self, ClockKind};
14use super::exact::{exact_number, DurationTiers, ExactNumber};
15use super::field::DurationLane;
16use super::field_rules::{
17    self, DateForm, EpochField, Fields, Sources, DAY_OF_QUARTER_KEYS, DAY_OF_WEEK_KEYS,
18    EPOCH_MILLIS_KEYS, EPOCH_SECONDS_KEYS, ORDINAL_DAY_KEYS,
19};
20use super::parse::{parse_iso, parse_pattern};
21use super::zone::{add_offset, apply_timezone, offset_from_map, IanaAt, ResolvedZone};
22use super::{
23    checked_lane, weekday_from_i, DurationField, Temporal, MONTHS_PER_QUARTER, NANOS_PER_SECOND,
24};
25
26/// The integer a temporal component map holds under `k`, or `None` when the
27/// field is absent or null. A present non-integer is Neo4j's 22G06
28/// non-assignable component (an `ArgumentError`): an integer-typed component
29/// map never reads a float/string/bool/list value as an absent field. Null is
30/// ignored, as Neo4j filters null-valued fields before constructing.
31pub(super) fn map_int(map: &Fields, k: &str) -> Result<Option<i64>> {
32    match map.get(k) {
33        None | Some(Value::Null) => Ok(None),
34        Some(Value::Int(v)) => Ok(Some(*v)),
35        Some(other) => Err(Error::argument_error(format!(
36            "cannot assign '{k}' of a {}",
37            bare_type_name(other)
38        ))),
39    }
40}
41
42/// [`map_int`] narrowed to the bounded integer a component stores (`u32` for
43/// a date/time field, `i32` for a calendar year). The one home of the
44/// conversion and its typed out-of-range error.
45pub(super) fn map_int_bounded<T>(map: &Fields, k: &str, msg: &str) -> Result<Option<T>>
46where
47    T: TryFrom<i64>,
48{
49    map_int(map, k)?
50        .map(|value| T::try_from(value).map_err(|_| Error::argument_error(msg)))
51        .transpose()
52}
53
54/// The first present spelling of a multi-spelling field (`dayOfWeek`/
55/// `dayofweek`), validated through [`map_int`]. The first spelling keeps the
56/// documented precedence when both are present.
57pub(super) fn map_int_alias(map: &Fields, keys: &[&str]) -> Result<Option<i64>> {
58    for key in keys {
59        if let Some(value) = map_int(map, key)? {
60            return Ok(Some(value));
61        }
62    }
63    Ok(None)
64}
65
66/// `(epoch seconds, subsecond nanos)` named by the epoch field `field` —
67/// the field [`field_rules::validate_epoch`] selected, read through its own
68/// key family, so the validator and the reader cannot disagree about which
69/// field names the instant.
70fn epoch_from_map(m: &Fields, field: EpochField) -> Result<(i64, u32)> {
71    // The validator proved one spelling carries a non-null value; the alias
72    // reader keeps the first-spelling precedence and the 22G06 rejection for
73    // a non-integer.
74    let value = map_int_alias(m, field.keys())?
75        .ok_or_else(|| Error::argument_error(format!("{} must be an integer", field.name())))?;
76    Ok(field.split(value))
77}
78
79/// The UTC naive datetime the selected epoch field names. Epoch fields are
80/// instants on the UTC timeline by definition, so the conversion itself
81/// needs no zone.
82fn epoch_utc_dt(m: &Fields, field: EpochField) -> Result<NaiveDateTime> {
83    let (secs, nanos) = epoch_from_map(m, field)?;
84    // `split` answers nanos already in `0..=999_999_999`, so no clamp or
85    // unchecked cast is needed here.
86    chrono::DateTime::from_timestamp(secs, nanos)
87        .map(|d| d.naive_utc())
88        .ok_or_else(|| Error::argument_error("epoch out of range"))
89}
90
91pub(super) fn date_from_parts(year: i32, month: u32, day: u32) -> Result<NaiveDate> {
92    NaiveDate::from_ymd_opt(year, month, day).ok_or_else(|| Error::argument_error("invalid date"))
93}
94
95pub(super) fn date_from_week(year: i32, week: u32, dow: Weekday) -> Result<NaiveDate> {
96    // chrono's `from_isoywd_opt` computes `year ± 1` internally *before* its
97    // range guard, so i32-extreme years (reachable here from week-date
98    // strings, e.g. '2147483647W526') panic inside chrono. Restrict to
99    // chrono's range ±1: the internal `year ± 1` then stays within i32 and
100    // any genuinely out-of-range result still returns `None`.
101    if !(-262_144..=262_144).contains(&year) {
102        return Err(Error::argument_error("invalid week date"));
103    }
104    NaiveDate::from_isoywd_opt(year, week, dow)
105        .ok_or_else(|| Error::argument_error("invalid week date"))
106}
107
108/// The typed constructor vocabulary: a clock kind or `duration`, the one
109/// non-clock constructor. Every name reader ([`is_constructor`],
110/// [`clock_kind`], [`construct_named`], [`accepts_pattern`]) classifies a
111/// spelling through [`Constructor::from_name`], so none can disagree on a
112/// spelling and none allocates to compare one.
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114enum Constructor {
115    Clock(ClockKind),
116    Duration,
117}
118
119impl Constructor {
120    /// The alias spellings and the base constructor each stands for; the
121    /// base spellings are the kind table's own ([`ClockKind::from_name_ignore_case`])
122    /// plus `duration`.
123    const ALIASES: &'static [(&'static str, Constructor)] = &[
124        ("local_time", Constructor::Clock(ClockKind::LocalTime)),
125        (
126            "local_datetime",
127            Constructor::Clock(ClockKind::LocalDateTime),
128        ),
129        (
130            "local_date_time",
131            Constructor::Clock(ClockKind::LocalDateTime),
132        ),
133        ("zoned_time", Constructor::Clock(ClockKind::Time)),
134        ("zoned_datetime", Constructor::Clock(ClockKind::DateTime)),
135        ("zoned_date_time", Constructor::Clock(ClockKind::DateTime)),
136    ];
137
138    /// The constructor `name` spells, case-insensitively and without
139    /// allocating; `None` for every non-constructor.
140    fn from_name(name: &str) -> Option<Self> {
141        if name.eq_ignore_ascii_case("duration") {
142            return Some(Self::Duration);
143        }
144        ClockKind::from_name_ignore_case(name)
145            .map(Self::Clock)
146            .or_else(|| {
147                Self::ALIASES
148                    .iter()
149                    .find(|(spelling, _)| spelling.eq_ignore_ascii_case(name))
150                    .map(|(_, ctor)| *ctor)
151            })
152    }
153
154    /// The base constructor spelling (`localdatetime`, `duration`, …).
155    fn base_name(self) -> &'static str {
156        match self {
157            Self::Clock(kind) => kind.name(),
158            Self::Duration => "duration",
159        }
160    }
161}
162
163/// Whether `name` is a temporal constructor spelling [`construct_named`]
164/// builds values from — a clock kind or `duration`, the one non-clock
165/// constructor. The one predicate the front-end's dialect gate and literal
166/// folding and the executor's scan-predicate specialization consult, so
167/// none can recognize a name the shared policy would not construct. The
168/// alias spellings (`local_time`, …) are recognized; the clock-access
169/// spellings are not constructors of arguments at all.
170pub fn is_constructor(name: &str) -> bool {
171    Constructor::from_name(name).is_some()
172}
173
174/// The clock kind `name` constructs, spellings canonicalized (`zoned_datetime`
175/// is [`ClockKind::DateTime`]); `None` for `duration` and every non-constructor.
176/// The typed form of [`is_constructor`] for a caller that decides per kind;
177/// it allocates nothing, so it is safe on a per-row path.
178pub fn clock_kind(name: &str) -> Option<ClockKind> {
179    match Constructor::from_name(name)? {
180        Constructor::Clock(kind) => Some(kind),
181        Constructor::Duration => None,
182    }
183}
184
185/// The base spelling `construct_named` and the pattern parser key on. A
186/// non-constructor keeps its case-folded spelling, which both consumers
187/// reject by name.
188fn base_spelling(name: &str) -> std::borrow::Cow<'static, str> {
189    match Constructor::from_name(name) {
190        Some(ctor) => std::borrow::Cow::Borrowed(ctor.base_name()),
191        None => std::borrow::Cow::Owned(name.to_ascii_lowercase()),
192    }
193}
194
195/// Whether `name` accepts the CIP-228 `(value, pattern)` form — every
196/// constructor does, so this is [`is_constructor`], the one vocabulary
197/// predicate.
198pub fn accepts_pattern(name: &str) -> bool {
199    is_constructor(name)
200}
201
202/// The three shapes a temporal constructor's map argument can take.
203enum MapForm {
204    /// An epoch field (`epochMillis`/`epochSeconds`) names an instant on the
205    /// UTC timeline.
206    Epoch,
207    /// The map's only constructor-relevant entry is a `timezone`: the
208    /// clock-reading form.
209    Clock,
210    /// Component fields — the field constructors' map.
211    Fields,
212}
213
214/// The one map-shape classifier, consulted once per constructor call. Its
215/// positive rules are the readers' own vocabulary — the epoch fields, the
216/// `timezone` selector, and (by exclusion) the component fields — so no
217/// second field list can drift from them. A map carrying an epoch field
218/// alongside `timezone` stays the epoch form; null-valued entries are
219/// ignored, as every field reader ignores them, so a null epoch spelling
220/// neither selects the epoch form nor hides the component fields beside it.
221/// A null `timezone` keeps the clock form so it is rejected as a timezone
222/// rather than read as an absent field.
223fn map_form(m: &Fields) -> MapForm {
224    if field_rules::present_alias(m, EPOCH_MILLIS_KEYS)
225        || field_rules::present_alias(m, EPOCH_SECONDS_KEYS)
226    {
227        return MapForm::Epoch;
228    }
229    if m.contains_key("timezone")
230        && m.iter()
231            .all(|(key, value)| key == "timezone" || value.is_null())
232    {
233        return MapForm::Clock;
234    }
235    MapForm::Fields
236}
237
238/// Whether a constructor argument is the clock-reading map form. The
239/// literal fold consults this: a clock reading samples the clock, so folding
240/// it would bake a lowering-time instant into the plan.
241pub fn samples_clock(arg: &Value) -> bool {
242    matches!(arg, Value::Map(m) if matches!(map_form(m), MapForm::Clock))
243}
244
245/// The map-argument policy for a clock-capable kind: an epoch field names
246/// an instant, a timezone-only map is the clock reading, every other map is
247/// the component-field map.
248fn construct_map(kind: ClockKind, m: &Fields) -> Result<Temporal> {
249    match map_form(m) {
250        MapForm::Epoch => epoch_map(kind, m),
251        MapForm::Clock => clock::clock_from_map(kind, m),
252        MapForm::Fields => {
253            let validated = field_rules::validate(kind, m)?;
254            field_map(kind, m, &validated)
255        }
256    }
257}
258
259/// The epoch map form: the instant the epoch field names, then every other
260/// component field applied over its wall clock in the resolved zone. The
261/// component-field policy is the one that reads those overrides, so the
262/// validator's "component fields and `timezone` stay legal overrides"
263/// contract and the reader cannot diverge (Neo4j-verified:
264/// `datetime({epochSeconds: 0, year: 2020})` is `2020-01-01T00:00Z`, and
265/// `{epochMillis: 0, minute: 5, timezone: '+02:00'}` is
266/// `1970-01-01T02:05+02:00`).
267fn epoch_map(kind: ClockKind, m: &Fields) -> Result<Temporal> {
268    let field = field_rules::validate_epoch(kind, m)?;
269    let utc = epoch_utc_dt(m, field)?;
270    let resolved = offset_from_map(m, IanaAt::Utc(utc))?;
271    // The instant's wall clock in the resolved zone is this map's source
272    // date/time; the epoch spellings are replaced by it and every other key
273    // (component fields, `timezone`) is carried through unchanged.
274    let mut component_map: Fields = m
275        .iter()
276        .filter(|(key, _)| !field_rules::is_epoch_field(key))
277        .map(|(key, value)| (key.clone(), value.clone()))
278        .collect();
279    component_map.insert(
280        "datetime".into(),
281        Value::Temporal(clock::zoned(utc, resolved)),
282    );
283    let validated = field_rules::validate(kind, &component_map)?;
284    field_map(kind, &component_map, &validated)
285}
286
287/// The component-field map constructor for `kind` — the map path for maps
288/// [`map_form`] classified as [`MapForm::Fields`] (and the epoch form, once
289/// its instant is the map's source), after [`field_rules::validate`] admitted
290/// the field set and resolved its form and sources.
291fn field_map(
292    kind: ClockKind,
293    m: &Fields,
294    validated: &field_rules::Validated<'_>,
295) -> Result<Temporal> {
296    let form = validated.form;
297    let sources = &validated.sources;
298    Ok(match kind {
299        ClockKind::Date => Temporal::Date(date_from_map(m, form, sources.date)?),
300        ClockKind::LocalTime => Temporal::LocalTime(time_from_map(m, sources)?),
301        ClockKind::Time => {
302            let time = time_from_map(m, sources)?;
303            // A `time` map has no date fields (`accepts` rejects them), so
304            // the date comes from a zoned `time` source or the epoch default.
305            let date = match sources.time {
306                Some(Temporal::DateTime { utc, offset, .. }) => add_offset(*utc, *offset)?.date(),
307                _ => date_from_parts(1970, 1, 1)?,
308            };
309            let (utc, resolved) = apply_timezone(date.and_time(time), m)?;
310            time_wall_clock(utc, resolved.offset)?
311        }
312        ClockKind::LocalDateTime => Temporal::LocalDateTime(
313            date_from_map(m, form, sources.date)?.and_time(time_from_map(m, sources)?),
314        ),
315        ClockKind::DateTime => {
316            let local = date_from_map(m, form, sources.date)?.and_time(time_from_map(m, sources)?);
317            let (utc, resolved) = apply_timezone(local, m)?;
318            clock::zoned(utc, resolved)
319        }
320    })
321}
322
323/// The one constructor entry: the clock reading (`None`), the value
324/// construction (`Some`), or the map policy — the five kinds differ only in
325/// the vocabulary the kind supplies.
326pub(super) fn construct(kind: ClockKind, arg: Option<&Value>) -> Result<Temporal> {
327    match arg {
328        None => Ok(now_value(kind)),
329        Some(Value::String(value)) => parse_iso(kind.name(), value),
330        // A duration is not a temporal source any clock constructor accepts:
331        // Neo4j reports it as the call's own failure — ProcedureCallFailed
332        // under 42001 (probed 2026-11-20 on 2026.10.1), not as a
333        // value-conversion failure.
334        Some(Value::Temporal(Temporal::Duration { .. })) => Err(Error::procedure_call(format!(
335            "Invalid call signature: {}() does not accept a duration",
336            kind.name()
337        ))),
338        Some(Value::Temporal(value)) => temporal_of(kind, value),
339        Some(Value::Map(m)) => construct_map(kind, m),
340        // Live reports every non-temporal, non-map single argument the same
341        // way (probed 2026-11-20 on 2026.10.1: date(123) and
342        // localdatetime(123) are both 42001).
343        Some(_) => Err(Error::procedure_call(format!(
344            "Invalid call signature: {}()",
345            kind.name()
346        ))),
347    }
348}
349
350/// The value conversion each kind applies to an existing temporal (`date(x)`,
351/// `time(x)`, …). `datetime` keeps a zoned source verbatim; `time` keeps the
352/// source's offset where it carries one. A source without the part a kind
353/// needs is a typed rejection (`datetime(date(…))`, `date(localtime(…))`).
354fn temporal_of(kind: ClockKind, value: &Temporal) -> Result<Temporal> {
355    Ok(match kind {
356        ClockKind::Date => Temporal::Date(date_of(value)?),
357        ClockKind::Time => {
358            let time = time_of(value).ok_or_else(|| Error::ty("cannot convert to time"))?;
359            let offset = match value {
360                Temporal::Time { offset, .. } | Temporal::DateTime { offset, .. } => *offset,
361                _ => 0,
362            };
363            Temporal::Time { time, offset }
364        }
365        ClockKind::LocalTime => time_of(value)
366            .map(Temporal::LocalTime)
367            .ok_or_else(|| Error::ty("cannot convert to localtime"))?,
368        // Every dated-and-timed source reads as its local wall clock; a
369        // source without both halves is the typed rejection.
370        ClockKind::LocalDateTime => match value {
371            Temporal::LocalDateTime(_)
372            | Temporal::CivilDateTime { .. }
373            | Temporal::DateTime { .. } => Temporal::LocalDateTime(local_dt_of(value)?),
374            _ => return Err(Error::ty("cannot convert to localdatetime")),
375        },
376        ClockKind::DateTime => match value {
377            Temporal::DateTime { .. } => value.clone(),
378            Temporal::LocalDateTime(_) | Temporal::CivilDateTime { .. } => {
379                clock::zoned(local_dt_of(value)?, ResolvedZone::utc())
380            }
381            _ => return Err(Error::ty("cannot convert to datetime")),
382        },
383    })
384}
385
386/// A constructor call with more than the two arguments the grammar
387/// defines. The message follows the executor's `invalid_arity` shape
388/// (`InvalidNumberOfArguments: <name>() requires <range>`); it is spelled
389/// here because core cannot call that helper (the dependency points the
390/// other way).
391fn too_many_arguments(name: &str, got: usize) -> Error {
392    Error::syntax(format!(
393        "InvalidNumberOfArguments: {name}() requires zero to two arguments, got {got}"
394    ))
395}
396
397/// The one name-keyed temporal construction policy: the spelling
398/// canonicalization (`local_time` → `localtime`, …), the two-argument
399/// `value, pattern` form, and the base constructors — shared by the
400/// executor's builtin dispatch, the scan-predicate specialization, and
401/// the front-end's literal folding, so no two of them can disagree on
402/// what `date("…")` means. Callers passing zero arguments get the clock
403/// reading (`QueryClockGuard` pins it per statement).
404pub fn construct_named(name: &str, vals: &[Value]) -> Result<Value> {
405    let canon = base_spelling(name);
406    match vals {
407        // The clock reading: the base constructor with no argument.
408        [] => base_value(&canon, None),
409        [Value::Null] => Ok(Value::Null),
410        [value] => base_value(&canon, Some(value)),
411        // CIP-228 `(value, pattern)`: a null on either side constructs null.
412        [value, pattern] => match (value, pattern) {
413            (Value::Null, _) | (_, Value::Null) => Ok(Value::Null),
414            (Value::String(value), Value::String(pattern)) => {
415                Ok(Value::Temporal(parse_pattern(&canon, value, pattern)?))
416            }
417            (Value::String(_), _) => Err(Error::invalid_argument_type("temporal pattern")),
418            // Live splits the operand faults by side: a non-string value is
419            // the call's own failure (ProcedureCallFailed under 42001,
420            // probed 2026-11-20 on 2026.10.1), while a non-string pattern
421            // stays the runtime Type mismatch (`InvalidArgumentType`, 22G03)
422            // the row above reports.
423            _ => Err(Error::procedure_call(format!(
424                "Invalid call signature for {name}: the value must be a STRING when a pattern is given"
425            ))),
426        },
427        // Every other arity is the typed arity rejection, never a silent
428        // construction from the first argument.
429        _ => Err(too_many_arguments(name, vals.len())),
430    }
431}
432
433/// The zero/one-argument construction: a clock kind through the one
434/// [`construct`] entry, `duration` through its own ISO/map constructor.
435fn base_value(canon: &str, arg: Option<&Value>) -> Result<Value> {
436    match ClockKind::from_name(canon) {
437        Some(kind) => construct(kind, arg).map(Value::Temporal),
438        None if canon == "duration" => construct_duration(arg).map(Value::Temporal),
439        None => Err(Error::ty("unknown temporal constructor")),
440    }
441}
442
443pub fn construct_date(arg: Option<&Value>) -> Result<Temporal> {
444    construct(ClockKind::Date, arg)
445}
446
447/// The calendar date a value reads as. A civil datetime's date is outside
448/// chrono's range by construction (that is why it is civil), so the reader
449/// answers the authored unreadable-source rejection rather than a generic
450/// conversion failure.
451pub(super) fn date_of(t: &Temporal) -> Result<NaiveDate> {
452    match t {
453        Temporal::Date(d) => Ok(*d),
454        Temporal::CivilDate { year, month, day } => {
455            // `as i32` would wrap extreme civil years into chrono range;
456            // convert honestly so only representable years can succeed.
457            let year =
458                i32::try_from(*year).map_err(|_| Error::ty("civil date out of chrono range"))?;
459            NaiveDate::from_ymd_opt(year, *month, *day)
460                .ok_or_else(|| Error::ty("civil date out of chrono range"))
461        }
462        Temporal::LocalDateTime(dt) => Ok(dt.date()),
463        Temporal::CivilDateTime { .. } => Err(field_rules::cannot_get_temporal("date", t)),
464        Temporal::DateTime { utc, offset, .. } => Ok(add_offset(*utc, *offset)?.date()),
465        _ => Err(Error::ty("cannot convert to date")),
466    }
467}
468
469/// The date a component map names, reading the fields of the form
470/// [`field_rules::validate`] resolved — so presence is decided once, and a
471/// null-valued form field cannot select a form here that the validator
472/// ignored (or vice versa). `source` is the validated `date`/`datetime`
473/// source temporal, supplying every form's defaults.
474fn date_from_map(
475    m: &Fields,
476    form: Option<DateForm>,
477    source: Option<&Temporal>,
478) -> Result<NaiveDate> {
479    let source = source.map(date_of).transpose()?;
480    match form {
481        Some(DateForm::Week) => week_from_map(m, source),
482        Some(DateForm::Ordinal) => ordinal_from_map(m, source),
483        Some(DateForm::Quarter) => quarter_from_map(m, source),
484        Some(DateForm::Calendar) | None => calendar_from_map(m, source),
485    }
486}
487
488/// The `year` field, else the source date's calendar year, else zero (the
489/// documented default of an unset year).
490fn year_from_map(m: &Fields, source: Option<NaiveDate>) -> Result<i32> {
491    Ok(map_int_bounded(m, "year", "invalid date")?
492        .or_else(|| source.map(|d| d.year()))
493        .unwrap_or(0))
494}
495
496/// The calendar form (`month`/`day` over the source date).
497fn calendar_from_map(m: &Fields, source: Option<NaiveDate>) -> Result<NaiveDate> {
498    let year = year_from_map(m, source)?;
499    let month = map_int_bounded(m, "month", "invalid date")?
500        .or_else(|| source.map(|d| d.month()))
501        .unwrap_or(1);
502    let day = map_int_bounded(m, "day", "invalid date")?
503        .or_else(|| source.map(|d| d.day()))
504        .unwrap_or(1);
505    date_from_parts(year, month, day)
506}
507
508/// The week form: the ISO week-year and weekday the source date falls in,
509/// overridden by the map's own `year`/`week`/`dayOfWeek`.
510fn week_from_map(m: &Fields, source: Option<NaiveDate>) -> Result<NaiveDate> {
511    let (default_year, default_week, default_dow) = match source {
512        Some(d) => (
513            d.iso_week().year(),
514            d.iso_week().week(),
515            i64::from(d.weekday().number_from_monday()),
516        ),
517        None => (0, 1, 1),
518    };
519    let year = map_int_bounded(m, "year", "invalid date")?.unwrap_or(default_year);
520    let week = map_int_bounded(m, "week", "invalid date")?.unwrap_or(default_week);
521    let dow = map_int_alias(m, DAY_OF_WEEK_KEYS)?.unwrap_or(default_dow);
522    date_from_week(year, week, weekday_from_i(dow))
523}
524
525/// The ordinal form: `year` plus `ordinalDay`.
526fn ordinal_from_map(m: &Fields, source: Option<NaiveDate>) -> Result<NaiveDate> {
527    let year = year_from_map(m, source)?;
528    // The ordinal form is selected by `ordinalDay` itself, so the non-null
529    // integer the validator admitted is what is read here.
530    let ordinal = map_int_alias(m, ORDINAL_DAY_KEYS)?
531        .expect("the ordinal form implies a non-null ordinalDay");
532    let ordinal = u32::try_from(ordinal).map_err(|_| Error::argument_error("invalid date"))?;
533    NaiveDate::from_yo_opt(year, ordinal).ok_or_else(|| Error::argument_error("invalid date"))
534}
535
536/// The quarter form: an optional `quarter` (defaulting to the source date's
537/// month, or January) and an optional `dayOfQuarter`.
538fn quarter_from_map(m: &Fields, source: Option<NaiveDate>) -> Result<NaiveDate> {
539    let year = year_from_map(m, source)?;
540    let default_month = source.map(|d| d.month()).unwrap_or(1);
541    let quarter = map_int(m, "quarter")?.unwrap_or_else(|| i64::from((default_month - 1) / 3 + 1));
542    // Quarter-of-year math on a user-controlled i64: compute in i128 and
543    // error on anything out of range instead of wrapping a u32. A quarter
544    // outside 1..=4, or `quarter: 0` (whose first month is not a month),
545    // reaches the typed `invalid date` error — never a silent clamp.
546    let quarter_month = |moq: u32| -> Result<u32> {
547        let month = (i128::from(quarter) - 1) * MONTHS_PER_QUARTER + i128::from(moq);
548        u32::try_from(month).map_err(|_| Error::argument_error("invalid date"))
549    };
550    let Some(day_of_quarter) = map_int_alias(m, DAY_OF_QUARTER_KEYS)? else {
551        // The month within the quarter keeps the source date's position, and
552        // its day of month carries over unchanged.
553        let moq = (default_month.saturating_sub(1) % 3) + 1;
554        let day = source.map(|d| d.day()).unwrap_or(1);
555        return date_from_parts(year, quarter_month(moq)?, day);
556    };
557    let dq = u32::try_from(day_of_quarter)
558        .ok()
559        .filter(|dq| *dq >= 1)
560        .ok_or_else(|| Error::argument_error("invalid date"))?;
561    let start = date_from_parts(year, quarter_month(1)?, 1)?;
562    start
563        .checked_add_days(Days::new(u64::from(dq - 1)))
564        .ok_or_else(|| Error::argument_error("invalid date"))
565}
566
567fn time_from_map(m: &Fields, sources: &Sources<'_>) -> Result<NaiveTime> {
568    // An embedded `time`/`datetime` value supplies the base clock; a map
569    // without one starts at midnight.
570    let base = sources.time.and_then(time_of).unwrap_or(NaiveTime::MIN);
571    time_from_map_with_base(base, m)
572}
573
574/// The time of day a component map names, overridden field by field on top
575/// of `base`. One override block shared by construction (base midnight or an
576/// embedded temporal) and truncation (base the truncated input's time).
577pub(super) fn time_from_map_with_base(base: NaiveTime, m: &Fields) -> Result<NaiveTime> {
578    let hour = map_int_bounded(m, "hour", "invalid time")?.unwrap_or(base.hour());
579    let minute = map_int_bounded(m, "minute", "invalid time")?.unwrap_or(base.minute());
580    let second = map_int_bounded(m, "second", "invalid time")?.unwrap_or(base.second());
581    let nano = nano_with_subsecond_fields(base.nanosecond(), m)?;
582    NaiveTime::from_hms_nano_opt(hour, minute, second, nano)
583        .ok_or_else(|| Error::argument_error("invalid time"))
584}
585
586/// The upper bound (exclusive) each sub-second field accepts in the map
587/// constructors. The finer fields' bounds narrow when a coarser sibling is
588/// present: `millisecond` always stops at 1000, `microsecond` at 1000 when
589/// milliseconds are supplied (else 1_000_000), and `nanosecond` at 1000 when
590/// microseconds are supplied, else 1_000_000 when milliseconds are, else
591/// 1_000_000_000. That is Neo4j's `validNano` rule, and the one place it is
592/// stated.
593fn subsecond_bound(coarser_present: bool, when_coarser: i64, otherwise: i64) -> i64 {
594    if coarser_present {
595        when_coarser
596    } else {
597        otherwise
598    }
599}
600
601/// Sum the subsecond map fields (`millisecond`/`microsecond`/`nanosecond`)
602/// into a nanosecond count, validating each field against its own range
603/// ([`subsecond_bound`]). A negative or over-range field is Neo4j's 22N03
604/// numeric-out-of-range error, never a wrapped contribution. The accumulation
605/// stays in i128 because the three i64 fields are user-controlled.
606fn nano_with_subsecond_fields(base: u32, m: &Fields) -> Result<u32> {
607    let millisecond = map_int(m, "millisecond")?;
608    let microsecond = map_int(m, "microsecond")?;
609    let nanosecond = map_int(m, "nanosecond")?;
610    let check = |field: &str, value: i64, bound: i64| -> Result<i64> {
611        if (0..bound).contains(&value) {
612            Ok(value)
613        } else {
614            Err(Error::argument_error(format!(
615                "specified numeric value out of range: expected {field} in the range 0 to {} but found {value}",
616                bound - 1
617            )))
618        }
619    };
620    let mut total = i128::from(base);
621    if let Some(ms) = millisecond {
622        total += i128::from(check("millisecond", ms, 1_000)?) * 1_000_000;
623    }
624    if let Some(us) = microsecond {
625        let bound = subsecond_bound(millisecond.is_some(), 1_000, 1_000_000);
626        total += i128::from(check("microsecond", us, bound)?) * 1_000;
627    }
628    if let Some(ns) = nanosecond {
629        let millis_bound = subsecond_bound(millisecond.is_some(), 1_000_000, 1_000_000_000);
630        let bound = subsecond_bound(microsecond.is_some(), 1_000, millis_bound);
631        total += i128::from(check("nanosecond", ns, bound)?);
632    }
633    let nanos = u32::try_from(total).map_err(|_| Error::argument_error("invalid time"))?;
634    // Chrono encodes a leap second as second 59 with a fraction >= 1e9 (up
635    // to 1_999_999_999) — the encoding `truncate_time` and its test
636    // deliberately preserve. The base can carry that encoding (an embedded
637    // time or an extras map reading an existing value); the user fields
638    // cannot reach 1e9 on their own (each component check bounds them and
639    // the bounds tighten when a coarser field is present), so the full
640    // representable range round-trips and only a genuinely over-range sum
641    // errors.
642    if nanos >= 2_000_000_000 {
643        return Err(Error::argument_error("invalid time"));
644    }
645    Ok(nanos)
646}
647
648/// The time of day a value reads as, or `None` when it carries none. The
649/// proleptic civil datetime answers its own wall clock, the same value
650/// [`Temporal::has_time`] admits.
651pub(super) fn time_of(t: &Temporal) -> Option<NaiveTime> {
652    match t {
653        Temporal::LocalTime(t) | Temporal::Time { time: t, .. } => Some(*t),
654        Temporal::LocalDateTime(dt) => Some(dt.time()),
655        Temporal::CivilDateTime { time, .. } => Some(*time),
656        Temporal::DateTime { utc, offset, .. } => utc
657            .checked_add_signed(ChronoDur::seconds(i64::from(*offset)))
658            .map(|local| local.time()),
659        _ => None,
660    }
661}
662
663pub fn construct_localtime(arg: Option<&Value>) -> Result<Temporal> {
664    construct(ClockKind::LocalTime, arg)
665}
666
667pub fn construct_time(arg: Option<&Value>) -> Result<Temporal> {
668    construct(ClockKind::Time, arg)
669}
670
671/// The wall-clock `Temporal::Time` of the UTC instant `utc` read at
672/// `offset` — the shared tail of `construct_time`'s epoch and field-map
673/// paths (F-1-20).
674fn time_wall_clock(utc: NaiveDateTime, offset: i32) -> Result<Temporal> {
675    let wall = add_offset(utc, offset)?;
676    Ok(Temporal::Time {
677        time: wall.time(),
678        offset,
679    })
680}
681
682pub fn construct_localdatetime(arg: Option<&Value>) -> Result<Temporal> {
683    construct(ClockKind::LocalDateTime, arg)
684}
685
686pub(super) fn local_dt_of(t: &Temporal) -> Result<NaiveDateTime> {
687    match t {
688        Temporal::LocalDateTime(dt) => Ok(*dt),
689        Temporal::Date(d) => Ok(d.and_time(NaiveTime::MIN)),
690        Temporal::DateTime { utc, offset, .. } => add_offset(*utc, *offset),
691        _ => Err(Error::ty("cannot convert to localdatetime")),
692    }
693}
694
695pub fn construct_datetime(arg: Option<&Value>) -> Result<Temporal> {
696    construct(ClockKind::DateTime, arg)
697}
698
699pub fn construct_duration(arg: Option<&Value>) -> Result<Temporal> {
700    match arg {
701        Some(Value::String(s)) => parse_iso("duration", s),
702        Some(Value::Temporal(t @ Temporal::Duration { .. })) => Ok(t.clone()),
703        Some(Value::Map(m)) => duration_from_map(m),
704        // Live reports the unconstructible argument as the call's own
705        // failure (duration(123) is 42001, probed 2026-11-20 on 2026.10.1).
706        _ => Err(Error::procedure_call("Invalid call signature: duration()")),
707    }
708}
709
710/// The duration a component map names. Every map key that names a duration
711/// field contributes through the one field table (`DurationField::from_map_key`);
712/// null fields are ignored, as Neo4j filters them before constructing, and a
713/// map with no non-null field names no unit (22N30). Integer-only maps take
714/// the exact i64 lane arithmetic; any float sends the whole map through the
715/// approximate f64 cascade, matching Neo4j's all-integral-values split.
716fn duration_from_map(m: &Fields) -> Result<Temporal> {
717    let mut values: std::collections::BTreeMap<DurationField, ExactNumber> =
718        std::collections::BTreeMap::new();
719    for (key, value) in m.iter().filter(|(_, value)| !value.is_null()) {
720        // A non-null field no duration unit names is Neo4j's
721        // `Unknown field: foo`; a null one was filtered above, like every
722        // other null field.
723        let field = DurationField::from_map_key(key)
724            .ok_or_else(|| Error::ty(format!("Unknown field: {key}")))?;
725        values.insert(field, exact_number(key, value)?);
726    }
727    if values.is_empty() {
728        return Err(field_rules::at_least_one_unit());
729    }
730    // Integer-only maps take the lane arithmetic; the all-integral split is
731    // taken once, here, so the lane sum never re-checks it.
732    let integers: Option<std::collections::BTreeMap<DurationField, i128>> = values
733        .iter()
734        .map(|(field, number)| number.as_int().map(|n| (*field, n)))
735        .collect();
736    if let Some(integers) = integers {
737        return integral_duration(&integers);
738    }
739    let mut tiers = DurationTiers::default();
740    for (field, number) in &values {
741        let slot = field.slot(&mut tiers);
742        slot.accumulator.add(*number, slot.scale)?;
743    }
744    let (months, days, nanos) = tiers.finish()?;
745    Temporal::duration_checked(months, days, nanos)
746}
747
748/// Build a duration from integer map fields through Neo4j's lane arithmetic:
749/// years/months, weeks/days, hours/minutes/seconds and the three sub-second
750/// fields each sum in one lane, then each lane is narrowed to i64 (22N28 on
751/// overflow) and the assembled value goes through [`Temporal::duration_checked`],
752/// the one representability seam every producer shares. Sub-second nanos fold
753/// into the seconds lane for that bound; the stored value keeps the exact i128
754/// nanosecond total.
755fn integral_duration(values: &std::collections::BTreeMap<DurationField, i128>) -> Result<Temporal> {
756    // Every lane is summed from the one field table
757    // ([`DurationField::lane_and_unit`], walked in cascade order), so a
758    // field added to the vocabulary cannot be dropped from a lane. An absent
759    // field contributes zero. The nanosecond tier splits at whole seconds: its
760    // seconds lane counts in seconds, its sub-second lane in nanoseconds.
761    let mut lanes = [0i128; DurationLane::COUNT];
762    for field in DurationField::CASCADE {
763        let Some(n) = values.get(&field) else {
764            continue;
765        };
766        let (lane, unit) = field.lane_and_unit();
767        lanes[lane as usize] += n * unit;
768    }
769    let lane = |lane: DurationLane| checked_lane(lanes[lane as usize], "duration()");
770    let months = lane(DurationLane::Months)?;
771    let days = lane(DurationLane::Days)?;
772    let seconds = lane(DurationLane::Seconds)?;
773    let subsecond = lane(DurationLane::SubSecond)?;
774    Temporal::duration_checked_exact(
775        months,
776        days,
777        i128::from(seconds) * NANOS_PER_SECOND + i128::from(subsecond),
778    )
779}