temps-core 4.0.0

Core functionality for temps - time and date parsing library
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! Error types for the temps library.
//!
//! This module defines the error types used throughout the temps ecosystem.
//! All parsing and date calculation operations return `Result<T, TempsError>`.
//!
//! # Error Categories
//!
//! - **Parse Errors**: When input cannot be parsed as a valid time expression
//! - **Date Calculation Errors**: When date arithmetic results in invalid dates
//! - **Invalid Component Errors**: When date/time components are out of range
//! - **Backend Errors**: When the underlying datetime library reports an error
//!
//! # Examples
//!
//! ```
//! use temps_core::{parse, Language, TempsError};
//!
//! // Parse error example
//! let result = parse("invalid input", Language::English);
//! match result {
//!     Err(TempsError::ParseError { message, input, position }) => {
//!         println!("Parse failed: {}", message);
//!     }
//!     _ => {}
//! }
//! ```

use thiserror::Error;

/// The main error type for the temps library.
///
/// This enum represents all possible errors that can occur during
/// parsing and time calculation operations.
#[derive(Error, Debug, Clone, PartialEq, Eq, Hash)]
pub enum TempsError {
    /// Error that occurs during parsing of time expressions.
    ///
    /// This error is returned when the input string cannot be parsed
    /// as a valid time expression in the specified language.
    ///
    /// # Example
    ///
    /// ```
    /// use temps_core::TempsError;
    ///
    /// let err = TempsError::parse_error("Unrecognized time unit", "in 5 blargs");
    /// ```
    #[error("Failed to parse time expression: {message}")]
    ParseError {
        /// The specific parsing error message
        message: String,
        /// The input that failed to parse
        input: String,
        /// Optional position in the input where parsing failed
        position: Option<usize>,
    },

    /// Error that occurs during date/time calculations.
    ///
    /// This error is returned when date arithmetic operations fail,
    /// such as when adding months to January 31st would result in
    /// February 31st (which doesn't exist).
    ///
    /// # Example
    ///
    /// ```
    /// use temps_core::TempsError;
    ///
    /// let err = TempsError::date_calculation("Month overflow");
    /// ```
    #[error("Date calculation error: {message}")]
    DateCalculationError {
        /// The specific calculation error message
        message: String,
        /// Optional context about what caused the error
        context: Option<String>,
    },

    /// Error for invalid date components
    #[error("Invalid date: year={year}, month={month}, day={day}")]
    InvalidDate {
        /// The year component
        year: u16,
        /// The month component (1-12)
        month: u8,
        /// The day component (1-31)
        day: u8,
    },

    /// Error for invalid time components
    #[error("Invalid time: {hour:02}:{minute:02}:{second:02}")]
    InvalidTime {
        /// The hour component (0-23)
        hour: u8,
        /// The minute component (0-59)
        minute: u8,
        /// The second component (0-59)
        second: u8,
    },

    /// Error for invalid timezone offset
    #[error("Invalid timezone offset: {hours:+03}:{minutes:02}")]
    InvalidTimezoneOffset {
        /// The hour offset (-12 to +14)
        hours: i8,
        /// The minute offset (0-59)
        minutes: u8,
    },

    /// Error for ambiguous local time (e.g., during DST transitions)
    #[error("Ambiguous local time: {message}")]
    AmbiguousTime {
        /// Description of the ambiguity
        message: String,
    },

    /// Error for arithmetic overflow in date calculations
    #[error("Arithmetic overflow: {operation}")]
    ArithmeticOverflow {
        /// The operation that caused the overflow
        operation: String,
    },

    /// Error for unsupported operations
    #[error("Unsupported operation: {operation}")]
    UnsupportedOperation {
        /// Description of the unsupported operation
        operation: String,
    },

    /// Error from the underlying datetime backend (chrono, jiff, etc.)
    #[error("Backend error: {message}")]
    BackendError {
        /// The error message from the backend
        message: String,
        /// The backend that produced the error
        backend: String,
    },
}

impl TempsError {
    /// Creates a new parse error without position information.
    ///
    /// Use this when you know parsing failed but don't have a specific
    /// position in the input where the error occurred.
    ///
    /// # Arguments
    ///
    /// * `message` - Description of what went wrong
    /// * `input` - The input string that failed to parse
    ///
    /// # Example
    ///
    /// ```
    /// use temps_core::TempsError;
    ///
    /// let err = TempsError::parse_error(
    ///     "Expected time unit",
    ///     "in 5"
    /// );
    /// ```
    #[must_use]
    pub fn parse_error(message: impl Into<String>, input: impl Into<String>) -> Self {
        Self::ParseError {
            message: message.into(),
            input: input.into(),
            position: None,
        }
    }

    /// Creates a new parse error with position information.
    ///
    /// Use this when you know exactly where in the input the parse error occurred.
    ///
    /// # Arguments
    ///
    /// * `message` - Description of what went wrong
    /// * `input` - The input string that failed to parse
    /// * `position` - Character position where parsing failed
    ///
    /// # Example
    ///
    /// ```
    /// use temps_core::TempsError;
    ///
    /// let err = TempsError::parse_error_with_position(
    ///     "Unexpected character",
    ///     "in 5 minuts",
    ///     9  // Points to the 't' in "minuts"
    /// );
    /// ```
    #[must_use]
    pub fn parse_error_with_position(
        message: impl Into<String>,
        input: impl Into<String>,
        position: usize,
    ) -> Self {
        Self::ParseError {
            message: message.into(),
            input: input.into(),
            position: Some(position),
        }
    }

    /// Creates a new date calculation error.
    ///
    /// Use this for errors that occur during date arithmetic operations.
    ///
    /// # Example
    ///
    /// ```
    /// use temps_core::TempsError;
    ///
    /// let err = TempsError::date_calculation(
    ///     "Cannot subtract 13 months from January"
    /// );
    /// ```
    #[must_use]
    pub fn date_calculation(message: impl Into<String>) -> Self {
        Self::DateCalculationError {
            message: message.into(),
            context: None,
        }
    }

    /// Creates a new date calculation error with additional context.
    ///
    /// Use this when you want to include information about what caused
    /// the calculation to fail (e.g., an error from the backend library).
    ///
    /// # Example
    ///
    /// ```
    /// use temps_core::TempsError;
    ///
    /// let err = TempsError::date_calculation_with_source(
    ///     "Failed to add months",
    ///     "chronos error: date out of range"
    /// );
    /// ```
    #[must_use]
    pub fn date_calculation_with_source(
        message: impl Into<String>,
        context: impl Into<String>,
    ) -> Self {
        Self::DateCalculationError {
            message: message.into(),
            context: Some(context.into()),
        }
    }

    /// Creates an invalid date error
    #[must_use]
    pub fn invalid_date(year: u16, month: u8, day: u8) -> Self {
        Self::InvalidDate { year, month, day }
    }

    /// Creates an invalid time error
    #[must_use]
    pub fn invalid_time(hour: u8, minute: u8, second: u8) -> Self {
        Self::InvalidTime {
            hour,
            minute,
            second,
        }
    }

    /// Creates an invalid timezone offset error
    #[must_use]
    pub fn invalid_timezone_offset(hours: i8, minutes: u8) -> Self {
        Self::InvalidTimezoneOffset { hours, minutes }
    }

    /// Creates an ambiguous time error
    #[must_use]
    pub fn ambiguous_time(message: impl Into<String>) -> Self {
        Self::AmbiguousTime {
            message: message.into(),
        }
    }

    /// Creates an arithmetic overflow error
    #[must_use]
    pub fn arithmetic_overflow(operation: impl Into<String>) -> Self {
        Self::ArithmeticOverflow {
            operation: operation.into(),
        }
    }

    /// Creates an unsupported operation error
    #[must_use]
    pub fn unsupported_operation(operation: impl Into<String>) -> Self {
        Self::UnsupportedOperation {
            operation: operation.into(),
        }
    }

    /// Creates a backend error
    #[must_use]
    pub fn backend_error(message: impl Into<String>, backend: impl Into<String>) -> Self {
        Self::BackendError {
            message: message.into(),
            backend: backend.into(),
        }
    }
}

/// Result type alias for temps operations.
///
/// All parsing and time calculation operations in the temps library
/// return this result type.
///
/// # Example
///
/// ```
/// use temps_core::Result;
///
/// fn parse_time(input: &str) -> Result<String> {
///     // Implementation
///     Ok("parsed".to_string())
/// }
/// ```
pub type Result<T> = std::result::Result<T, TempsError>;

/// Convert a collection of chumsky parser errors into a [`TempsError`]
/// and an ariadne-rendered diagnostic string.
///
/// The first error's span is used for the position field. The full
/// rendered report (with source context) is folded into the error's
/// message so callers that simply display the error still get a useful,
/// human-readable diagnostic.
#[must_use]
pub fn rich_errors_to_temps_error(
    input: &str,
    errors: Vec<chumsky::error::Rich<'_, char>>,
) -> TempsError {
    use ariadne::{Color, Label, Report, ReportKind, Source};

    if input.is_empty() {
        return TempsError::parse_error_with_position(
            "input is empty; expected a time expression like `now`, `in 5 minutes`, or an ISO date",
            input,
            0,
        );
    }

    let position = errors.first().map(|e| e.span().start).unwrap_or(0);

    let source_id: &str = "input";
    let mut rendered = String::new();
    for err in &errors {
        let span = err.span();
        let range = span.start..span.end.max(span.start + 1).min(input.len().max(1));
        let mut buf = Vec::new();
        let (headline, detail) = format_rich(err);
        let report = Report::build(ReportKind::Error, (source_id, range.clone()))
            .with_message(headline)
            .with_label(
                Label::new((source_id, range))
                    .with_message(detail)
                    .with_color(Color::Red),
            )
            .finish();

        if report
            .write((source_id, Source::from(input)), &mut buf)
            .is_ok()
        {
            rendered.push_str(&String::from_utf8_lossy(&buf));
        } else {
            rendered.push_str(&err.to_string());
            rendered.push('\n');
        }
    }

    let message = if rendered.is_empty() {
        "Failed to parse time expression".to_string()
    } else {
        rendered.trim_end().to_string()
    };

    TempsError::parse_error_with_position(message, input, position)
}

/// Render a chumsky [`Rich`](chumsky::error::Rich) error as a `(headline, detail)`
/// pair suitable for an ariadne report.
fn format_rich(err: &chumsky::error::Rich<'_, char>) -> (String, String) {
    use chumsky::error::RichReason;

    match err.reason() {
        RichReason::Custom(msg) => ("invalid time expression".to_string(), msg.clone()),
        _ => {
            let found = match err.found() {
                Some(c) => format!("`{}`", c.escape_default()),
                None => "end of input".to_string(),
            };

            let mut seen = std::collections::BTreeSet::new();
            let mut expected: Vec<String> = Vec::new();
            for pat in err.expected() {
                let rendered = pat.to_string();
                if seen.insert(rendered.clone()) {
                    expected.push(rendered);
                }
            }

            let detail = match expected.as_slice() {
                [] => format!("unexpected {found}"),
                [one] => format!("expected {one}, found {found}"),
                many => {
                    let last = many.last().expect("non-empty");
                    let head = &many[..many.len() - 1];
                    format!(
                        "expected one of {} or {}, found {found}",
                        head.join(", "),
                        last
                    )
                }
            };

            ("could not parse time expression".to_string(), detail)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_error_display() {
        let err = TempsError::invalid_date(2024, 13, 32);
        assert_eq!(err.to_string(), "Invalid date: year=2024, month=13, day=32");

        let err = TempsError::invalid_time(25, 61, 61);
        assert_eq!(err.to_string(), "Invalid time: 25:61:61");

        let err = TempsError::parse_error("unexpected token", "in 5 minuts");
        assert_eq!(
            err.to_string(),
            "Failed to parse time expression: unexpected token"
        );
    }

    #[test]
    fn test_error_creation_helpers() {
        let err = TempsError::date_calculation("month out of range");
        match err {
            TempsError::DateCalculationError { message, context } => {
                assert_eq!(message, "month out of range");
                assert!(context.is_none());
            }
            _ => panic!("Wrong error type"),
        }

        let err = TempsError::backend_error("conversion failed", "chrono");
        match err {
            TempsError::BackendError { message, backend } => {
                assert_eq!(message, "conversion failed");
                assert_eq!(backend, "chrono");
            }
            _ => panic!("Wrong error type"),
        }
    }
}