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
108pub fn is_constructor(name: &str) -> bool {
117 let canon = canonical(name);
118 canon == "duration" || ClockKind::from_name(&canon).is_some()
119}
120
121fn canonical(name: &str) -> String {
127 match name.to_ascii_lowercase().as_str() {
128 "local_time" => "localtime".to_string(),
129 "local_datetime" | "local_date_time" => "localdatetime".to_string(),
130 "zoned_time" => "time".to_string(),
131 "zoned_datetime" | "zoned_date_time" => "datetime".to_string(),
132 other => other.to_string(),
133 }
134}
135
136pub fn accepts_pattern(name: &str) -> bool {
140 is_constructor(name)
141}
142
143enum MapForm {
145 Epoch,
148 Clock,
151 Fields,
153}
154
155fn map_form(m: &Fields) -> MapForm {
165 if field_rules::present_alias(m, EPOCH_MILLIS_KEYS)
166 || field_rules::present_alias(m, EPOCH_SECONDS_KEYS)
167 {
168 return MapForm::Epoch;
169 }
170 if m.contains_key("timezone")
171 && m.iter()
172 .all(|(key, value)| key == "timezone" || value.is_null())
173 {
174 return MapForm::Clock;
175 }
176 MapForm::Fields
177}
178
179pub fn samples_clock(arg: &Value) -> bool {
183 matches!(arg, Value::Map(m) if matches!(map_form(m), MapForm::Clock))
184}
185
186fn construct_map(kind: ClockKind, m: &Fields) -> Result<Temporal> {
190 match map_form(m) {
191 MapForm::Epoch => epoch_map(kind, m),
192 MapForm::Clock => clock::clock_from_map(kind, m),
193 MapForm::Fields => {
194 let validated = field_rules::validate(kind, m)?;
195 field_map(kind, m, &validated)
196 }
197 }
198}
199
200fn epoch_map(kind: ClockKind, m: &Fields) -> Result<Temporal> {
209 let field = field_rules::validate_epoch(kind, m)?;
210 let utc = epoch_utc_dt(m, field)?;
211 let resolved = offset_from_map(m, IanaAt::Utc(utc))?;
212 let mut component_map: Fields = m
216 .iter()
217 .filter(|(key, _)| !field_rules::is_epoch_field(key))
218 .map(|(key, value)| (key.clone(), value.clone()))
219 .collect();
220 component_map.insert(
221 "datetime".into(),
222 Value::Temporal(clock::zoned(utc, resolved)),
223 );
224 let validated = field_rules::validate(kind, &component_map)?;
225 field_map(kind, &component_map, &validated)
226}
227
228fn field_map(
233 kind: ClockKind,
234 m: &Fields,
235 validated: &field_rules::Validated<'_>,
236) -> Result<Temporal> {
237 let form = validated.form;
238 let sources = &validated.sources;
239 Ok(match kind {
240 ClockKind::Date => Temporal::Date(date_from_map(m, form, sources.date)?),
241 ClockKind::LocalTime => Temporal::LocalTime(time_from_map(m, sources)?),
242 ClockKind::Time => {
243 let time = time_from_map(m, sources)?;
244 let date = match sources.time {
247 Some(Temporal::DateTime { utc, offset, .. }) => add_offset(*utc, *offset)?.date(),
248 _ => date_from_parts(1970, 1, 1)?,
249 };
250 let (utc, resolved) = apply_timezone(date.and_time(time), m)?;
251 time_wall_clock(utc, resolved.offset)?
252 }
253 ClockKind::LocalDateTime => Temporal::LocalDateTime(
254 date_from_map(m, form, sources.date)?.and_time(time_from_map(m, sources)?),
255 ),
256 ClockKind::DateTime => {
257 let local = date_from_map(m, form, sources.date)?.and_time(time_from_map(m, sources)?);
258 let (utc, resolved) = apply_timezone(local, m)?;
259 clock::zoned(utc, resolved)
260 }
261 })
262}
263
264fn construct(kind: ClockKind, arg: Option<&Value>) -> Result<Temporal> {
268 match arg {
269 None => Ok(now_value(kind)),
270 Some(Value::String(value)) => parse_iso(kind.name(), value),
271 Some(Value::Temporal(Temporal::Duration { .. })) => Err(Error::syntax(format!(
275 "Invalid call signature: {}() does not accept a duration",
276 kind.name()
277 ))),
278 Some(Value::Temporal(value)) => temporal_of(kind, value),
279 Some(Value::Map(m)) => construct_map(kind, m),
280 Some(_) => Err(Error::syntax(format!(
281 "Invalid call signature: {}()",
282 kind.name()
283 ))),
284 }
285}
286
287fn temporal_of(kind: ClockKind, value: &Temporal) -> Result<Temporal> {
292 Ok(match kind {
293 ClockKind::Date => Temporal::Date(date_of(value)?),
294 ClockKind::Time => {
295 let time = time_of(value).ok_or_else(|| Error::ty("cannot convert to time"))?;
296 let offset = match value {
297 Temporal::Time { offset, .. } | Temporal::DateTime { offset, .. } => *offset,
298 _ => 0,
299 };
300 Temporal::Time { time, offset }
301 }
302 ClockKind::LocalTime => time_of(value)
303 .map(Temporal::LocalTime)
304 .ok_or_else(|| Error::ty("cannot convert to localtime"))?,
305 ClockKind::LocalDateTime => match value {
308 Temporal::LocalDateTime(_)
309 | Temporal::CivilDateTime { .. }
310 | Temporal::DateTime { .. } => Temporal::LocalDateTime(local_dt_of(value)?),
311 _ => return Err(Error::ty("cannot convert to localdatetime")),
312 },
313 ClockKind::DateTime => match value {
314 Temporal::DateTime { .. } => value.clone(),
315 Temporal::LocalDateTime(_) | Temporal::CivilDateTime { .. } => {
316 clock::zoned(local_dt_of(value)?, ResolvedZone::utc())
317 }
318 _ => return Err(Error::ty("cannot convert to datetime")),
319 },
320 })
321}
322
323fn too_many_arguments(name: &str, got: usize) -> Error {
329 Error::syntax(format!(
330 "InvalidNumberOfArguments: {name}() requires zero to two arguments, got {got}"
331 ))
332}
333
334pub fn construct_named(name: &str, vals: &[Value]) -> Result<Value> {
342 let canon = canonical(name);
343 match vals {
344 [] => base_value(&canon, None),
346 [Value::Null] => Ok(Value::Null),
347 [value] => base_value(&canon, Some(value)),
348 [value, pattern] => match (value, pattern) {
350 (Value::Null, _) | (_, Value::Null) => Ok(Value::Null),
351 (Value::String(value), Value::String(pattern)) => {
352 Ok(Value::Temporal(parse_pattern(&canon, value, pattern)?))
353 }
354 (Value::String(_), _) => Err(Error::invalid_argument_type("temporal pattern")),
355 _ => Err(Error::invalid_argument_type("temporal value")),
356 },
357 _ => Err(too_many_arguments(name, vals.len())),
360 }
361}
362
363fn base_value(canon: &str, arg: Option<&Value>) -> Result<Value> {
366 match ClockKind::from_name(canon) {
367 Some(kind) => construct(kind, arg).map(Value::Temporal),
368 None if canon == "duration" => construct_duration(arg).map(Value::Temporal),
369 None => Err(Error::ty("unknown temporal constructor")),
370 }
371}
372
373pub fn construct_date(arg: Option<&Value>) -> Result<Temporal> {
374 construct(ClockKind::Date, arg)
375}
376
377pub(super) fn date_of(t: &Temporal) -> Result<NaiveDate> {
382 match t {
383 Temporal::Date(d) => Ok(*d),
384 Temporal::CivilDate { year, month, day } => {
385 let year =
388 i32::try_from(*year).map_err(|_| Error::ty("civil date out of chrono range"))?;
389 NaiveDate::from_ymd_opt(year, *month, *day)
390 .ok_or_else(|| Error::ty("civil date out of chrono range"))
391 }
392 Temporal::LocalDateTime(dt) => Ok(dt.date()),
393 Temporal::CivilDateTime { .. } => Err(field_rules::cannot_get_temporal("date", t)),
394 Temporal::DateTime { utc, offset, .. } => Ok(add_offset(*utc, *offset)?.date()),
395 _ => Err(Error::ty("cannot convert to date")),
396 }
397}
398
399fn date_from_map(
405 m: &Fields,
406 form: Option<DateForm>,
407 source: Option<&Temporal>,
408) -> Result<NaiveDate> {
409 let source = source.map(date_of).transpose()?;
410 match form {
411 Some(DateForm::Week) => week_from_map(m, source),
412 Some(DateForm::Ordinal) => ordinal_from_map(m, source),
413 Some(DateForm::Quarter) => quarter_from_map(m, source),
414 Some(DateForm::Calendar) | None => calendar_from_map(m, source),
415 }
416}
417
418fn year_from_map(m: &Fields, source: Option<NaiveDate>) -> Result<i32> {
421 Ok(map_int_bounded(m, "year", "invalid date")?
422 .or_else(|| source.map(|d| d.year()))
423 .unwrap_or(0))
424}
425
426fn calendar_from_map(m: &Fields, source: Option<NaiveDate>) -> Result<NaiveDate> {
428 let year = year_from_map(m, source)?;
429 let month = map_int_bounded(m, "month", "invalid date")?
430 .or_else(|| source.map(|d| d.month()))
431 .unwrap_or(1);
432 let day = map_int_bounded(m, "day", "invalid date")?
433 .or_else(|| source.map(|d| d.day()))
434 .unwrap_or(1);
435 date_from_parts(year, month, day)
436}
437
438fn week_from_map(m: &Fields, source: Option<NaiveDate>) -> Result<NaiveDate> {
441 let (default_year, default_week, default_dow) = match source {
442 Some(d) => (
443 d.iso_week().year(),
444 d.iso_week().week(),
445 i64::from(d.weekday().number_from_monday()),
446 ),
447 None => (0, 1, 1),
448 };
449 let year = map_int_bounded(m, "year", "invalid date")?.unwrap_or(default_year);
450 let week = map_int_bounded(m, "week", "invalid date")?.unwrap_or(default_week);
451 let dow = map_int_alias(m, DAY_OF_WEEK_KEYS)?.unwrap_or(default_dow);
452 date_from_week(year, week, weekday_from_i(dow))
453}
454
455fn ordinal_from_map(m: &Fields, source: Option<NaiveDate>) -> Result<NaiveDate> {
457 let year = year_from_map(m, source)?;
458 let ordinal = map_int_alias(m, ORDINAL_DAY_KEYS)?
461 .expect("the ordinal form implies a non-null ordinalDay");
462 let ordinal = u32::try_from(ordinal).map_err(|_| Error::argument_error("invalid date"))?;
463 NaiveDate::from_yo_opt(year, ordinal).ok_or_else(|| Error::argument_error("invalid date"))
464}
465
466fn quarter_from_map(m: &Fields, source: Option<NaiveDate>) -> Result<NaiveDate> {
469 let year = year_from_map(m, source)?;
470 let default_month = source.map(|d| d.month()).unwrap_or(1);
471 let quarter = map_int(m, "quarter")?.unwrap_or_else(|| i64::from((default_month - 1) / 3 + 1));
472 let quarter_month = |moq: u32| -> Result<u32> {
477 let month = (i128::from(quarter) - 1) * MONTHS_PER_QUARTER + i128::from(moq);
478 u32::try_from(month).map_err(|_| Error::argument_error("invalid date"))
479 };
480 let Some(day_of_quarter) = map_int_alias(m, DAY_OF_QUARTER_KEYS)? else {
481 let moq = (default_month.saturating_sub(1) % 3) + 1;
484 let day = source.map(|d| d.day()).unwrap_or(1);
485 return date_from_parts(year, quarter_month(moq)?, day);
486 };
487 let dq = u32::try_from(day_of_quarter)
488 .ok()
489 .filter(|dq| *dq >= 1)
490 .ok_or_else(|| Error::argument_error("invalid date"))?;
491 let start = date_from_parts(year, quarter_month(1)?, 1)?;
492 start
493 .checked_add_days(Days::new(u64::from(dq - 1)))
494 .ok_or_else(|| Error::argument_error("invalid date"))
495}
496
497fn time_from_map(m: &Fields, sources: &Sources<'_>) -> Result<NaiveTime> {
498 let base = sources.time.and_then(time_of).unwrap_or(NaiveTime::MIN);
501 time_from_map_with_base(base, m)
502}
503
504pub(super) fn time_from_map_with_base(base: NaiveTime, m: &Fields) -> Result<NaiveTime> {
508 let hour = map_int_bounded(m, "hour", "invalid time")?.unwrap_or(base.hour());
509 let minute = map_int_bounded(m, "minute", "invalid time")?.unwrap_or(base.minute());
510 let second = map_int_bounded(m, "second", "invalid time")?.unwrap_or(base.second());
511 let nano = nano_with_subsecond_fields(base.nanosecond(), m)?;
512 NaiveTime::from_hms_nano_opt(hour, minute, second, nano)
513 .ok_or_else(|| Error::argument_error("invalid time"))
514}
515
516fn subsecond_bound(coarser_present: bool, when_coarser: i64, otherwise: i64) -> i64 {
524 if coarser_present {
525 when_coarser
526 } else {
527 otherwise
528 }
529}
530
531fn nano_with_subsecond_fields(base: u32, m: &Fields) -> Result<u32> {
537 let millisecond = map_int(m, "millisecond")?;
538 let microsecond = map_int(m, "microsecond")?;
539 let nanosecond = map_int(m, "nanosecond")?;
540 let check = |field: &str, value: i64, bound: i64| -> Result<i64> {
541 if (0..bound).contains(&value) {
542 Ok(value)
543 } else {
544 Err(Error::argument_error(format!(
545 "specified numeric value out of range: expected {field} in the range 0 to {} but found {value}",
546 bound - 1
547 )))
548 }
549 };
550 let mut total = i128::from(base);
551 if let Some(ms) = millisecond {
552 total += i128::from(check("millisecond", ms, 1_000)?) * 1_000_000;
553 }
554 if let Some(us) = microsecond {
555 let bound = subsecond_bound(millisecond.is_some(), 1_000, 1_000_000);
556 total += i128::from(check("microsecond", us, bound)?) * 1_000;
557 }
558 if let Some(ns) = nanosecond {
559 let millis_bound = subsecond_bound(millisecond.is_some(), 1_000_000, 1_000_000_000);
560 let bound = subsecond_bound(microsecond.is_some(), 1_000, millis_bound);
561 total += i128::from(check("nanosecond", ns, bound)?);
562 }
563 let nanos = u32::try_from(total).map_err(|_| Error::argument_error("invalid time"))?;
564 if nanos >= 2_000_000_000 {
573 return Err(Error::argument_error("invalid time"));
574 }
575 Ok(nanos)
576}
577
578pub(super) fn time_of(t: &Temporal) -> Option<NaiveTime> {
582 match t {
583 Temporal::LocalTime(t) | Temporal::Time { time: t, .. } => Some(*t),
584 Temporal::LocalDateTime(dt) => Some(dt.time()),
585 Temporal::CivilDateTime { time, .. } => Some(*time),
586 Temporal::DateTime { utc, offset, .. } => utc
587 .checked_add_signed(ChronoDur::seconds(i64::from(*offset)))
588 .map(|local| local.time()),
589 _ => None,
590 }
591}
592
593pub fn construct_localtime(arg: Option<&Value>) -> Result<Temporal> {
594 construct(ClockKind::LocalTime, arg)
595}
596
597pub fn construct_time(arg: Option<&Value>) -> Result<Temporal> {
598 construct(ClockKind::Time, arg)
599}
600
601fn time_wall_clock(utc: NaiveDateTime, offset: i32) -> Result<Temporal> {
605 let wall = add_offset(utc, offset)?;
606 Ok(Temporal::Time {
607 time: wall.time(),
608 offset,
609 })
610}
611
612pub fn construct_localdatetime(arg: Option<&Value>) -> Result<Temporal> {
613 construct(ClockKind::LocalDateTime, arg)
614}
615
616pub(super) fn local_dt_of(t: &Temporal) -> Result<NaiveDateTime> {
617 match t {
618 Temporal::LocalDateTime(dt) => Ok(*dt),
619 Temporal::Date(d) => Ok(d.and_time(NaiveTime::MIN)),
620 Temporal::DateTime { utc, offset, .. } => add_offset(*utc, *offset),
621 _ => Err(Error::ty("cannot convert to localdatetime")),
622 }
623}
624
625pub fn construct_datetime(arg: Option<&Value>) -> Result<Temporal> {
626 construct(ClockKind::DateTime, arg)
627}
628
629pub fn construct_duration(arg: Option<&Value>) -> Result<Temporal> {
630 match arg {
631 Some(Value::String(s)) => parse_iso("duration", s),
632 Some(Value::Temporal(t @ Temporal::Duration { .. })) => Ok(t.clone()),
633 Some(Value::Map(m)) => duration_from_map(m),
634 _ => Err(Error::syntax("Invalid call signature: duration()")),
635 }
636}
637
638fn duration_from_map(m: &Fields) -> Result<Temporal> {
645 let mut values: std::collections::BTreeMap<DurationField, ExactNumber> =
646 std::collections::BTreeMap::new();
647 for (key, value) in m.iter().filter(|(_, value)| !value.is_null()) {
648 let field = DurationField::from_map_key(key)
652 .ok_or_else(|| Error::ty(format!("Unknown field: {key}")))?;
653 values.insert(field, exact_number(key, value)?);
654 }
655 if values.is_empty() {
656 return Err(field_rules::at_least_one_unit());
657 }
658 let integers: Option<std::collections::BTreeMap<DurationField, i128>> = values
661 .iter()
662 .map(|(field, number)| number.as_int().map(|n| (*field, n)))
663 .collect();
664 if let Some(integers) = integers {
665 return integral_duration(&integers);
666 }
667 let mut tiers = DurationTiers::default();
668 for (field, number) in &values {
669 let slot = field.slot(&mut tiers);
670 slot.accumulator.add(*number, slot.scale)?;
671 }
672 let (months, days, nanos) = tiers.finish()?;
673 Temporal::duration_checked(months, days, nanos)
674}
675
676fn integral_duration(values: &std::collections::BTreeMap<DurationField, i128>) -> Result<Temporal> {
684 let mut lanes = [0i128; DurationLane::COUNT];
690 for field in DurationField::CASCADE {
691 let Some(n) = values.get(&field) else {
692 continue;
693 };
694 let (lane, unit) = field.lane_and_unit();
695 lanes[lane as usize] += n * unit;
696 }
697 let lane = |lane: DurationLane| checked_lane(lanes[lane as usize], "duration()");
698 let months = lane(DurationLane::Months)?;
699 let days = lane(DurationLane::Days)?;
700 let seconds = lane(DurationLane::Seconds)?;
701 let subsecond = lane(DurationLane::SubSecond)?;
702 Temporal::duration_checked_exact(
703 months,
704 days,
705 i128::from(seconds) * NANOS_PER_SECOND + i128::from(subsecond),
706 )
707}