use crate::plugins::{syntax, time};
use crate::{Context, Error, re};
use chrono::{
DateTime, Duration, FixedOffset, LocalResult, NaiveDate, NaiveDateTime, NaiveTime, TimeZone,
Timelike, Utc,
};
use chrono_tz::Tz;
fn invalid() -> Error {
Error("invalid_endpoint".into())
}
fn offset(input: &str) -> Option<FixedOffset> {
let c = re!(r"(?i)^(?:UTC)?([+-])(\d{1,2})(?::(\d{2}))?$").captures(input)?;
let hours: i32 = c[2].parse().ok()?;
let minutes: i32 = c.get(3).map_or(Some(0), |m| m.as_str().parse().ok())?;
if hours > 23 || minutes > 59 {
return None;
}
FixedOffset::east_opt((hours * 3600 + minutes * 60) * if &c[1] == "-" { -1 } else { 1 })
}
pub(super) fn zone_token(input: &str) -> bool {
input.parse::<Tz>().is_ok() || offset(input).is_some() || time::abbreviation(input).is_some()
}
#[derive(Clone, Copy)]
enum Zone {
Named(Tz),
Fixed(FixedOffset),
}
struct Endpoint {
local: NaiveDateTime,
zone: Zone,
instant: DateTime<Utc>,
}
fn read(input: &str, context: &Context, inherited: Option<&Endpoint>) -> Result<Endpoint, Error> {
let input = syntax::ungroup(input);
let c = re!(r"^(?:(\d{4}-\d{2}-\d{2})[ T])?(\d{2}:\d{2}(?::\d{2})?)(?:(?:,\s*|\s+)(.+))?$")
.captures(input)
.ok_or_else(invalid)?;
let date = if let Some(date) = c.get(1) {
NaiveDate::parse_from_str(date.as_str(), "%Y-%m-%d").map_err(|_| invalid())?
} else {
inherited.ok_or_else(invalid)?.local.date()
};
let clock =
NaiveTime::parse_from_str(&c[2], if c[2].len() == 5 { "%H:%M" } else { "%H:%M:%S" })
.map_err(|_| invalid())?;
let local = date.and_time(clock);
let suffix = c.get(3).map_or("", |m| m.as_str());
let suffix = if let Some(annotation) = re!(r"^(.*?)\s*\(([^()]*)\)(.*)$").captures(suffix) {
if annotation[2].trim().is_empty() {
return Err(invalid());
}
format!("{} {} {}", &annotation[1], &annotation[2], &annotation[3])
} else {
suffix.to_owned()
};
if suffix.trim().starts_with(',')
|| suffix.trim().ends_with(',')
|| re!(r",\s*,").is_match(&suffix)
{
return Err(invalid());
}
let suffix = suffix.replace(',', " ");
let tokens = suffix.split_whitespace().collect::<Vec<_>>();
let mut named = None;
let mut offsets = Vec::new();
let mut occurrence = None;
let mut at = 0;
while at < tokens.len() {
let token = tokens[at];
if token.eq_ignore_ascii_case("first") || token.eq_ignore_ascii_case("second") {
if occurrence
.replace(token.eq_ignore_ascii_case("second"))
.is_some()
{
return Err(invalid());
}
at += 1;
if tokens
.get(at)
.is_some_and(|s| s.eq_ignore_ascii_case("occurrence"))
{
at += 1;
}
if tokens.get(at).is_some_and(|s| s.eq_ignore_ascii_case("in")) {
at += 1;
if !tokens.get(at).is_some_and(|s| zone_token(s)) {
return Err(invalid());
}
}
continue;
}
if let Ok(zone) = token.parse::<Tz>()
&& (token.eq_ignore_ascii_case("UTC") || time::abbreviation(token).is_none())
{
if named.is_some_and(|previous| previous != zone) {
return Err(invalid());
}
named = Some(zone);
} else if let Some(fixed) = offset(token).or_else(|| time::abbreviation(token)) {
offsets.push(fixed);
} else {
return Err(invalid());
}
at += 1;
}
let inherited_zone = inherited
.filter(|_| c.get(1).is_none() || occurrence.is_some())
.map(|point| point.zone);
let zone = if let Some(zone) = named {
Zone::Named(zone)
} else if occurrence.is_some() {
match inherited_zone {
Some(Zone::Named(zone)) => Zone::Named(zone),
_ => Zone::Named(context.timezone),
}
} else if !offsets.is_empty() && !matches!(inherited_zone, Some(Zone::Named(_))) {
Zone::Fixed(offsets[0])
} else {
inherited_zone.unwrap_or(Zone::Named(context.timezone))
};
let mut candidates = match zone {
Zone::Named(zone) => match zone.from_local_datetime(&local) {
LocalResult::Single(point) => vec![point.fixed_offset()],
LocalResult::Ambiguous(a, b) => vec![a.fixed_offset(), b.fixed_offset()],
LocalResult::None => return Err(Error("nonexistent_endpoint".into())),
},
Zone::Fixed(zone) => vec![
zone.from_local_datetime(&local)
.single()
.ok_or_else(invalid)?,
],
};
candidates.sort();
if let Some(second) = occurrence {
if candidates.len() != 2 {
return Err(invalid());
}
candidates = vec![candidates[usize::from(second)]];
}
candidates.retain(|point| offsets.iter().all(|offset| point.offset() == offset));
let point = match candidates.as_slice() {
[] => return Err(invalid()),
[point] => point.with_timezone(&Utc),
_ => return Err(Error("ambiguous_endpoint".into())),
};
Ok(Endpoint {
local,
zone,
instant: point,
})
}
pub(super) fn resolve(input: &str, context: &Context) -> Result<DateTime<Utc>, Error> {
read(input, context, None).map(|point| point.instant)
}
pub(super) fn shifted(input: &str, seconds: i64, context: &Context) -> Result<String, Error> {
let point = read(input, context, None)?;
let instant = point
.instant
.checked_add_signed(Duration::try_seconds(seconds).ok_or_else(invalid)?)
.ok_or_else(invalid)?;
let (local, zone) = match point.zone {
Zone::Named(zone) => (instant.with_timezone(&zone).naive_local(), zone.to_string()),
Zone::Fixed(zone) => (instant.with_timezone(&zone).naive_local(), zone.to_string()),
};
Ok(format!(
"calendar_instant({}|{}|{zone})",
local.date(),
local.time().num_seconds_from_midnight()
))
}
pub(super) fn elapsed(
start: &str,
end: &str,
context: &Context,
signed: bool,
) -> Result<i64, Error> {
let start = read(start, context, None)?;
let end = read(end, context, Some(&start))?;
if !signed && end.instant < start.instant {
return Err(Error("invalid_interval".into()));
}
Ok((end.instant - start.instant).num_seconds())
}
pub(super) struct Query {
pub start: String,
pub end: String,
pub target: String,
pub signed: bool,
}
fn query(start: &str, end: &str, target: &str, signed: bool) -> Query {
Query {
start: start.into(),
end: end.into(),
target: target.to_ascii_lowercase(),
signed,
}
}
fn goal(input: &str) -> Option<(String, bool)> {
let input = input.trim();
if let Some(c) = re!(r"(?i)^(?:in|expressed in) (.+)$").captures(input) {
return Some((c[1].to_ascii_lowercase(), false));
}
if let Some(c) = re!(r"(?i)^(?:find|calculate|give|report|determine)(?: the| its)? (?:(?:actual|real) )?(signed )?elapsed (hours and minutes|hours|minutes|seconds)$").captures(input) {
return Some((c[2].to_ascii_lowercase(), c.get(1).is_some()));
}
if let Some(c) = re!(r"(?i)^(?:find|calculate|give|report|determine)(?: the| its)? (?:(signed) )?(?:elapsed duration|(?:(?:actual|real) )?duration|real elapsed time) in (.+?)(?: across the clock change)?$").captures(input) {
return Some((c[2].to_ascii_lowercase(), c.get(1).is_some()));
}
if re!(r"(?i)^(?:how many elapsed hours and minutes passed|how long is the real elapsed interval|accounting for the local daylight-saving transition|(?:calculate|find) elapsed duration using the stated time zones)$").is_match(input) {
return Some(("hours and minutes".into(), false));
}
None
}
pub(super) fn wording(input: &str) -> Option<Query> {
let components =
re!(r"(?i)^(.+?)[,;] (?:report|give|find|calculate) elapsed days, hours, and minutes$");
if let Some(c) = components.captures(input)
&& let Some(mut result) = wording(&format!("{}, in seconds", &c[1]))
{
result.target = "days hours minutes".into();
return Some(result);
}
if let Some(c) = re!(r"(?i)^how long between (.+?) and (.+)$").captures(input) {
return Some(query(&c[1], &c[2], "minutes", false));
}
if let Some(c) = re!(r"(?i)^how much time passes from (.+?) to (.+)$").captures(input)
&& syntax::split_last(input, &[", ", "; "])
.and_then(|(_, tail)| goal(tail))
.is_none()
{
return Some(query(
c[1].trim_end_matches(',').trim_end(),
&c[2],
"hours and minutes",
false,
));
}
if let Some(c) =
re!(r"(?i)^how much time elapsed between (.+?) and (.+?), in (.+)$").captures(input)
{
return Some(query(&c[1], &c[2], &c[3], false));
}
if let Some(c) = re!(r"(?i)^(?:find|calculate) (?:the )?(signed )?elapsed (hours|minutes|seconds) from (.+?) to (.+)$").captures(input) {
return Some(query(&c[3], &c[4], &c[2], c.get(1).is_some()));
}
if let Some(c) = re!(r"(?i)^calculate (?:elapsed time|the interval) from (.+?) to (.+?),? in (hours|minutes|seconds)$").captures(input) {
return Some(query(&c[1], &c[2], &c[3], false));
}
if let Some(c) = re!(r"(?i)^how many full days and remaining hours are between (.+?) and (.+)$")
.captures(input)
{
return Some(query(&c[1], &c[2], "full days and remaining hours", false));
}
if let Some(c) =
re!(r"(?i)^(?:find|calculate) elapsed time from (.+?) to (.+)$").captures(input)
{
return Some(query(&c[1], &c[2], "minutes", false));
}
if let Some(c) = re!(r"(?i)^in ([^,]+), find elapsed time from (.+?) to (.+)$").captures(input)
{
return Some(query(
&format!("{} {}", &c[2], &c[1]),
&format!("{} {}", &c[3], &c[1]),
"minutes",
false,
));
}
if let Some(c) =
re!(r"(?i)^(?:for|on) (\d{4}-\d{2}-\d{2})(?: in ([^,]+))?, (.+)$").captures(input)
&& let Some(mut result) = wording(&c[3])
{
let zone = c.get(2).map_or("", |s| s.as_str());
let numbered_clock = re!(
r"(?i)^(?:the )?(first|second) (\d{2}:\d{2}(?::\d{2})?)(?: ([^ ]+))? occurrence(?: in ([^ ]+))?$"
);
let numbered_occurrence = re!(
r"(?i)^(?:the )?(first|second) occurrence(?: in ([^ ]+))? at (\d{2}:\d{2}(?::\d{2})?)(?: ([^ ]+))?$"
);
let scoped = |clock: &str| {
if let Some(p) = numbered_clock.captures(clock) {
format!(
"{} {} {} {} {} occurrence {}",
&c[1],
&p[2],
zone,
p.get(3).map_or("", |s| s.as_str()),
&p[1],
p.get(4).map_or("", |s| s.as_str())
)
} else if let Some(p) = numbered_occurrence.captures(clock) {
format!(
"{} {} {} {} {} occurrence {}",
&c[1],
&p[3],
zone,
p.get(4).map_or("", |s| s.as_str()),
&p[1],
p.get(2).map_or("", |s| s.as_str())
)
} else if let Some(p) =
re!(r"(?i)^(?:the )?(first|second) (\d{2}:\d{2}(?::\d{2})?)(?: (.+))?$")
.captures(clock)
{
format!(
"{} {} {} {} occurrence {}",
&c[1],
&p[2],
zone,
&p[1],
p.get(3).map_or("", |s| s.as_str())
)
} else if let Some(p) =
re!(r"(?i)^(\d{2}:\d{2}(?::\d{2})?)(?: (.+?))? on the (first|second) occurrence$")
.captures(clock)
{
format!(
"{} {} {} {} {} occurrence",
&c[1],
&p[1],
zone,
p.get(2).map_or("", |s| s.as_str()),
&p[3]
)
} else {
format!("{} {clock} {zone}", &c[1])
}
};
result.start = scoped(&result.start);
result.end = scoped(&result.end);
return Some(result);
}
if let Some(c) = re!(r"(?i)^in ([^,]+), (how much actual time elapses|calculate elapsed minutes) from (.+?) to (.+?)(?: across the spring clock change)?$").captures(input) {
let target = if c[2].eq_ignore_ascii_case("calculate elapsed minutes") {
"minutes"
} else {
"hours and minutes"
};
return Some(query(
&format!("{} {}", &c[3], &c[1]),
&format!("{} {}", &c[4], &c[1]),
target,
false,
));
}
if let Some(c) = re!(r"(?i)^for ([^ ]+) on (\d{4}-\d{2}-\d{2}), find the elapsed time from the (first|second) (\d{2}:\d{2}(?::\d{2})?) occurrence in ([a-z]+) to the (first|second) (\d{2}:\d{2}(?::\d{2})?) occurrence in ([a-z]+)$").captures(input) {
return Some(query(
&format!("{} {} {} {} occurrence {}", &c[2], &c[4], &c[1], &c[3], &c[5]),
&format!("{} {} {} {} occurrence {}", &c[2], &c[7], &c[1], &c[6], &c[8]),
"hours and minutes",
false,
));
}
if let Some(c) = re!(r"(?i)^for (\d{4}-\d{2}-\d{2}) in ([^,]+), find actual elapsed minutes from (.+?) to (.+?) during the skipped-hour transition$").captures(input) {
return Some(query(
&format!("{} {} {}", &c[1], &c[3], &c[2]),
&format!("{} {} {}", &c[1], &c[4], &c[2]),
"minutes",
false,
));
}
if let Some(c) = re!(
r"(?i)^a local appointment begins at (.+?),? and ends at (.+?); how many minutes passed$"
)
.captures(input)
{
return Some(query(&c[1], &c[2], "minutes", false));
}
if let Some(c) =
re!(r"(?i)^how many (seconds|minutes|hours) separate (.+?) and (.+)$").captures(input)
{
return Some(query(&c[2], &c[3], &c[1], false));
}
if let Some(c) = re!(r"(?i)^find (?:the number of (seconds)|the elapsed (minutes|hours|seconds)) between (.+?) and (.+)$").captures(input) {
let target = c.get(1).or_else(|| c.get(2))?;
return Some(query(&c[3], &c[4], target.as_str(), false));
}
if let Some(c) =
re!(r"(?i)^what is the elapsed duration in (.+?) between (.+?) and (.+)$").captures(input)
{
return Some(query(&c[2], &c[3], &c[1], false));
}
let (body, tail) = syntax::split_last(input, &[", ", "; "])?;
let (target, signed) = goal(tail)?;
if let Some(c) = re!(r"(?i)^(?:from|how much time passes from|calculate (?:elapsed time|the duration) from|how long is the interval from) (.+?) to (.+)$").captures(body) {
return Some(query(&c[1], &c[2], &target, signed));
}
if let Some(c) = re!(r"(?i)^(?:between|how long between) (.+?) and (.+)$").captures(body) {
return Some(query(&c[1], &c[2], &target, signed));
}
if let Some(c) = re!(r"(?i)^a (?:call|meeting|conference|train|webinar|reservation|flight) (?:begins at|starts at|leaves at|leaves|runs from|departs at) (.+?),? (?:and ends at|and arrives at|and lands|until|to) (.+)$").captures(body) {
return Some(query(&c[1], &c[2], &target, signed));
}
None
}