1use 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
26pub(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
42pub(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
54pub(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
66fn epoch_from_map(m: &Fields, field: EpochField) -> Result<(i64, u32)> {
71 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
79fn epoch_utc_dt(m: &Fields, field: EpochField) -> Result<NaiveDateTime> {
83 let (secs, nanos) = epoch_from_map(m, field)?;
84 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114enum Constructor {
115 Clock(ClockKind),
116 Duration,
117}
118
119impl Constructor {
120 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 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 fn base_name(self) -> &'static str {
156 match self {
157 Self::Clock(kind) => kind.name(),
158 Self::Duration => "duration",
159 }
160 }
161}
162
163pub fn is_constructor(name: &str) -> bool {
171 Constructor::from_name(name).is_some()
172}
173
174pub 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
185fn 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
195pub fn accepts_pattern(name: &str) -> bool {
199 is_constructor(name)
200}
201
202enum MapForm {
204 Epoch,
207 Clock,
210 Fields,
212}
213
214fn 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
238pub fn samples_clock(arg: &Value) -> bool {
242 matches!(arg, Value::Map(m) if matches!(map_form(m), MapForm::Clock))
243}
244
245fn 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
259fn 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 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
287fn 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 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
323pub(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 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 Some(_) => Err(Error::procedure_call(format!(
344 "Invalid call signature: {}()",
345 kind.name()
346 ))),
347 }
348}
349
350fn 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 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
386fn 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
397pub fn construct_named(name: &str, vals: &[Value]) -> Result<Value> {
405 let canon = base_spelling(name);
406 match vals {
407 [] => base_value(&canon, None),
409 [Value::Null] => Ok(Value::Null),
410 [value] => base_value(&canon, Some(value)),
411 [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 _ => 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 _ => Err(too_many_arguments(name, vals.len())),
430 }
431}
432
433fn 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
447pub(super) fn date_of(t: &Temporal) -> Result<NaiveDate> {
452 match t {
453 Temporal::Date(d) => Ok(*d),
454 Temporal::CivilDate { year, month, day } => {
455 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
469fn 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
488fn 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
496fn 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
508fn 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
525fn ordinal_from_map(m: &Fields, source: Option<NaiveDate>) -> Result<NaiveDate> {
527 let year = year_from_map(m, source)?;
528 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
536fn 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 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 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 let base = sources.time.and_then(time_of).unwrap_or(NaiveTime::MIN);
571 time_from_map_with_base(base, m)
572}
573
574pub(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
586fn 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
601fn 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 if nanos >= 2_000_000_000 {
643 return Err(Error::argument_error("invalid time"));
644 }
645 Ok(nanos)
646}
647
648pub(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
671fn 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 _ => Err(Error::procedure_call("Invalid call signature: duration()")),
707 }
708}
709
710fn 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 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 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
748fn integral_duration(values: &std::collections::BTreeMap<DurationField, i128>) -> Result<Temporal> {
756 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}