nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! Explicit local clocks resolve to UTC only after every supplied constraint agrees.
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;
    }
    // Bare clocks share their first endpoint's date and zone. Full dated
    // endpoints resolve independently, except an occurrence assertion needs
    // the named fold supplied by the first endpoint or configured context.
    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)
}
/// An elapsed shift keeps the supplied zone; it does not add local calendar days.
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| {
            // Preserve named-zone and abbreviation assertions whichever side of
            // the clock the authored occurrence appears on.
            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
}