gollum-ir 0.4.0

Intermediate Representation for the Gollum language
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
//! Timestamp and Interval types with native RON/serde support.
//!
//! Uses i64 for seconds and i32 for nanoseconds:
//! - i64 seconds range: ±9.2 × 10^18 seconds ≈ ±292 billion years
//! - i32 nanos range: 0 to 999,999,999

use chrono::{DateTime, NaiveDate, NaiveDateTime, TimeZone, Utc};
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::fmt;

const NANOS_PER_SECOND: i128 = 1_000_000_000;
const NANOS_PER_MINUTE: i128 = 60 * NANOS_PER_SECOND;
const NANOS_PER_HOUR: i128 = 60 * NANOS_PER_MINUTE;
const NANOS_PER_DAY: i128 = 24 * NANOS_PER_HOUR;
const NANOS_PER_WEEK: i128 = 7 * NANOS_PER_DAY;
const NANOS_PER_YEAR: i128 = 36525 * NANOS_PER_DAY / 100;

/// Timestamp with nanosecond precision.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Timestamp {
    /// Seconds since Unix epoch.
    pub seconds: i64,
    /// Nanosecond fraction (0 to 999,999,999).
    pub nanos: i32,
}

impl Timestamp {
    /// Creates a new Timestamp if nanos is in valid range.
    pub fn new(seconds: i64, nanos: i64) -> Option<Self> {
        if !(0i64..NANOS_PER_SECOND as i64).contains(&nanos) {
            return None;
        }
        Some(Self {
            seconds,
            nanos: nanos as i32,
        })
    }

    /// Creates a Timestamp from total nanoseconds since epoch.
    pub fn from_ns(ns: i128) -> Option<Self> {
        let seconds = (ns / NANOS_PER_SECOND) as i64;
        let nanos = (ns % NANOS_PER_SECOND) as i32;
        Some(Self { seconds, nanos })
    }

    /// Returns total nanoseconds since epoch.
    pub fn to_ns(self) -> i128 {
        (self.seconds as i128) * NANOS_PER_SECOND + (self.nanos as i128)
    }

    /// Parses a timestamp from various string formats.
    pub fn parse(input: &str) -> Result<Self, TimestampParseError> {
        let input = input.trim();

        if let Ok(dt) = DateTime::parse_from_rfc3339(input) {
            return Ok(dt.with_timezone(&Utc).into());
        }

        if let Ok(dt) = NaiveDateTime::parse_from_str(input, "%Y-%m-%dT%H:%M:%S%.f") {
            return Ok(Self::from_naivedt(dt));
        }
        if let Ok(dt) = NaiveDateTime::parse_from_str(input, "%Y-%m-%dT%H:%M:%S") {
            return Ok(Self::from_naivedt(dt));
        }
        if let Ok(dt) = NaiveDateTime::parse_from_str(input, "%Y-%m-%d %H:%M:%S") {
            return Ok(Self::from_naivedt(dt));
        }

        if let Ok(d) = NaiveDate::parse_from_str(input, "%Y-%m-%d") {
            return Ok(Self::from_naivedate(d));
        }

        parse_unit_literal(input)
    }

    fn from_naivedt(dt: NaiveDateTime) -> Self {
        Self {
            seconds: dt.and_utc().timestamp(),
            nanos: dt.and_utc().timestamp_subsec_nanos() as i32,
        }
    }

    fn from_naivedate(d: NaiveDate) -> Self {
        let dt = d.and_hms_opt(0, 0, 0).unwrap();
        Self {
            seconds: dt.and_utc().timestamp(),
            nanos: 0,
        }
    }

    /// Returns the Unix epoch (1970-01-01T00:00:00).
    pub fn epoch() -> Self {
        Self {
            seconds: 0,
            nanos: 0,
        }
    }
}

impl fmt::Display for Timestamp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match Utc.timestamp_opt(self.seconds, self.nanos as u32) {
            chrono::LocalResult::Single(dt) => {
                if self.nanos == 0 {
                    write!(f, "{}", dt.format("%Y-%m-%dT%H:%M:%S"))
                } else {
                    write!(f, "{}", dt.format("%Y-%m-%dT%H:%M:%S%.9f"))
                }
            }
            _ => write!(f, "{}s {}ns", self.seconds, self.nanos),
        }
    }
}

impl PartialOrd for Timestamp {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Timestamp {
    fn cmp(&self, other: &Self) -> Ordering {
        match self.seconds.cmp(&other.seconds) {
            Ordering::Equal => self.nanos.cmp(&other.nanos),
            other => other,
        }
    }
}

impl From<DateTime<Utc>> for Timestamp {
    fn from(dt: DateTime<Utc>) -> Self {
        Self {
            seconds: dt.timestamp(),
            nanos: dt.timestamp_subsec_nanos() as i32,
        }
    }
}

impl From<Timestamp> for DateTime<Utc> {
    fn from(ts: Timestamp) -> Self {
        Utc.timestamp_opt(ts.seconds, ts.nanos as u32)
            .single()
            .unwrap_or_else(Utc::now)
    }
}

/// Time interval with start and end timestamps.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Interval {
    /// Start of the interval.
    pub start: Timestamp,
    /// End of the interval.
    pub end: Timestamp,
}

impl Interval {
    /// Creates a new Interval if start <= end.
    pub fn new(start: Timestamp, end: Timestamp) -> Option<Self> {
        if start <= end {
            Some(Self { start, end })
        } else {
            None
        }
    }

    /// Creates an Interval from nanosecond timestamps.
    pub fn from_ns(start_ns: i128, end_ns: i128) -> Option<Self> {
        let start = Timestamp::from_ns(start_ns)?;
        let end = Timestamp::from_ns(end_ns)?;
        Self::new(start, end)
    }

    /// Returns true if this interval overlaps with another.
    pub fn overlaps(self, other: Interval) -> bool {
        self.start < other.end && other.start < self.end
    }

    /// Returns true if this interval ends before another starts.
    pub fn before(self, other: Interval) -> bool {
        self.end <= other.start
    }

    /// Returns true if this interval is contained within another.
    pub fn during(self, container: Interval) -> bool {
        container.start <= self.start && self.end <= container.end
    }

    /// Returns true if this interval's end meets the other's start.
    pub fn meets(self, other: Interval) -> bool {
        self.end == other.start
    }
}

impl fmt::Display for Interval {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[{}, {}]", self.start, self.end)
    }
}

/// Errors that can occur when parsing timestamps.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub enum TimestampParseError {
    /// Unknown time unit (e.g., "xyz" in "100xyz").
    #[error("invalid unit '{unit}' in '{input}'")]
    UnknownUnit {
        /// The full input string.
        input: String,
        /// The unknown unit found.
        unit: String,
    },

    /// Invalid number format.
    #[error("invalid number '{input}': {reason}")]
    InvalidNumber {
        /// The input that failed to parse.
        input: String,
        /// Reason for the failure.
        reason: String,
    },

    /// Missing time unit after number.
    #[error("missing unit in '{input}'")]
    MissingUnit {
        /// The input that was missing a unit.
        input: String,
    },
}

fn parse_unit_literal(input: &str) -> Result<Timestamp, TimestampParseError> {
    let input = input.trim();

    if input.is_empty() {
        return Err(TimestampParseError::MissingUnit {
            input: input.to_string(),
        });
    }

    let mut num_end = 0;
    let mut has_dot = false;
    for (i, c) in input.char_indices() {
        match c {
            '0'..='9' => num_end = i + 1,
            '-' if i == 0 => num_end = i + 1,
            '.' if !has_dot => {
                has_dot = true;
                num_end = i + 1;
            }
            _ => break,
        }
    }

    if num_end == 0 {
        return Err(TimestampParseError::InvalidNumber {
            input: input.to_string(),
            reason: "no numeric characters found".to_string(),
        });
    }

    let num_str = &input[..num_end];
    let unit = &input[num_end..];

    if unit.is_empty() {
        return Err(TimestampParseError::MissingUnit {
            input: input.to_string(),
        });
    }

    let nanos_per_unit: i128 = match unit {
        "ns" => 1,
        "us" | "µs" => 1_000,
        "ms" => 1_000_000,
        "s" => NANOS_PER_SECOND,
        "min" => NANOS_PER_MINUTE,
        "h" => NANOS_PER_HOUR,
        "d" => NANOS_PER_DAY,
        "w" => NANOS_PER_WEEK,
        "y" => NANOS_PER_YEAR,
        _ => {
            return Err(TimestampParseError::UnknownUnit {
                input: input.to_string(),
                unit: unit.to_string(),
            })
        }
    };

    let num: f64 = num_str.parse().map_err(|e: std::num::ParseFloatError| {
        TimestampParseError::InvalidNumber {
            input: num_str.to_string(),
            reason: e.to_string(),
        }
    })?;

    let total_ns = num as i128 * nanos_per_unit;

    // Check for overflow/underflow (very large values become 0 when cast)
    if total_ns / nanos_per_unit != num as i128 {
        return Err(TimestampParseError::InvalidNumber {
            input: input.to_string(),
            reason: "overflow".to_string(),
        });
    }

    Timestamp::from_ns(total_ns).ok_or_else(|| TimestampParseError::InvalidNumber {
        input: input.to_string(),
        reason: "out of range".to_string(),
    })
}

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

    #[test]
    fn test_timestamp_epoch() {
        let ts = Timestamp::epoch();
        assert_eq!(ts.seconds, 0);
        assert_eq!(ts.nanos, 0);
    }

    #[test]
    fn test_timestamp_from_ns() {
        let ts = Timestamp::from_ns(1_500_000_000).unwrap();
        assert_eq!(ts.seconds, 1);
        assert_eq!(ts.nanos, 500_000_000);
    }

    #[test]
    fn test_timestamp_to_ns() {
        let ts = Timestamp {
            seconds: 1,
            nanos: 500_000_000,
        };
        assert_eq!(ts.to_ns(), 1_500_000_000);
    }

    #[test]
    fn test_parse_unit_seconds() {
        let ts = Timestamp::parse("100s").unwrap();
        assert_eq!(ts.seconds, 100);
        assert_eq!(ts.nanos, 0);
    }

    #[test]
    fn test_parse_unit_milliseconds() {
        let ts = Timestamp::parse("1500ms").unwrap();
        assert_eq!(ts.seconds, 1);
        assert_eq!(ts.nanos, 500_000_000);
    }

    #[test]
    fn test_parse_negative() {
        let ts = Timestamp::parse("-3600s").unwrap();
        assert_eq!(ts.seconds, -3600);
        assert_eq!(ts.nanos, 0);
    }

    #[test]
    fn test_parse_iso_date() {
        let ts = Timestamp::parse("2020-01-01").unwrap();
        let expected = NaiveDate::from_ymd_opt(2020, 1, 1)
            .unwrap()
            .and_hms_opt(0, 0, 0)
            .unwrap();
        assert_eq!(ts.seconds, expected.and_utc().timestamp());
    }

    #[test]
    fn test_parse_iso_datetime() {
        let ts = Timestamp::parse("2020-01-01T12:30:00").unwrap();
        let expected = NaiveDate::from_ymd_opt(2020, 1, 1)
            .unwrap()
            .and_hms_opt(12, 30, 0)
            .unwrap();
        assert_eq!(ts.seconds, expected.and_utc().timestamp());
    }

    #[test]
    fn test_timestamp_ordering() {
        let ts1 = Timestamp::parse("100s").unwrap();
        let ts2 = Timestamp::parse("200s").unwrap();
        let ts3 = Timestamp::parse("100s").unwrap();

        assert!(ts1 < ts2);
        assert!(ts2 > ts1);
        assert!(ts1 <= ts3);
        assert!(ts1 >= ts3);
    }

    #[test]
    fn test_interval_new_valid() {
        let start = Timestamp::parse("100s").unwrap();
        let end = Timestamp::parse("200s").unwrap();
        let interval = Interval::new(start, end).unwrap();
        assert_eq!(interval.start, start);
        assert_eq!(interval.end, end);
    }

    #[test]
    fn test_interval_new_invalid() {
        let start = Timestamp::parse("200s").unwrap();
        let end = Timestamp::parse("100s").unwrap();
        assert!(Interval::new(start, end).is_none());
    }

    #[test]
    fn test_interval_overlaps() {
        let i1 = Interval::new(
            Timestamp::parse("0s").unwrap(),
            Timestamp::parse("100s").unwrap(),
        )
        .unwrap();
        let i2 = Interval::new(
            Timestamp::parse("50s").unwrap(),
            Timestamp::parse("150s").unwrap(),
        )
        .unwrap();
        let i3 = Interval::new(
            Timestamp::parse("100s").unwrap(),
            Timestamp::parse("200s").unwrap(),
        )
        .unwrap();

        assert!(i1.overlaps(i2));
        assert!(!i1.overlaps(i3));
    }

    #[test]
    fn test_interval_before() {
        let i1 = Interval::new(
            Timestamp::parse("0s").unwrap(),
            Timestamp::parse("100s").unwrap(),
        )
        .unwrap();
        let i2 = Interval::new(
            Timestamp::parse("100s").unwrap(),
            Timestamp::parse("200s").unwrap(),
        )
        .unwrap();
        let i3 = Interval::new(
            Timestamp::parse("50s").unwrap(),
            Timestamp::parse("150s").unwrap(),
        )
        .unwrap();

        assert!(i1.before(i2));
        assert!(!i1.before(i3));
    }

    #[test]
    fn test_interval_meets() {
        let i1 = Interval::new(
            Timestamp::parse("0s").unwrap(),
            Timestamp::parse("100s").unwrap(),
        )
        .unwrap();
        let i2 = Interval::new(
            Timestamp::parse("100s").unwrap(),
            Timestamp::parse("200s").unwrap(),
        )
        .unwrap();
        let i3 = Interval::new(
            Timestamp::parse("50s").unwrap(),
            Timestamp::parse("150s").unwrap(),
        )
        .unwrap();

        assert!(i1.meets(i2));
        assert!(!i1.meets(i3));
    }

    #[test]
    fn test_interval_display() {
        let interval = Interval::new(
            Timestamp::parse("100s").unwrap(),
            Timestamp::parse("200s").unwrap(),
        )
        .unwrap();
        let s = interval.to_string();
        assert!(s.starts_with('['), "should start with '[': {}", s);
        assert!(s.ends_with(']'), "should end with ']': {}", s);
        assert!(s.contains("T"), "should contain timestamp separator: {}", s);
    }
}