shape-ast 0.1.8

AST types and Pest grammar for the Shape programming 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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! Temporal expression parsing
//!
//! This module handles parsing of time-related expressions:
//! - Time references (@today, @yesterday, "2024-01-01")
//! - DateTime expressions
//! - Duration expressions (1h, 5m30s, 2 days)
//! - Temporal navigation expressions
//! - Relative time expressions

use super::super::pair_span;
use crate::ast::{
    DateTimeExpr, Duration, DurationUnit, Expr, NamedTime, RelativeTime, TimeDirection,
    TimeReference, TimeUnit, Timeframe,
};
use crate::error::{Result, ShapeError};
use crate::parser::Rule;
use crate::parser::string_literals::parse_string_literal;
use pest::iterators::Pair;

/// Parse a time reference
pub fn parse_time_ref(pair: Pair<Rule>) -> Result<TimeReference> {
    let inner = pair.into_inner().next().unwrap();

    match inner.as_rule() {
        Rule::quoted_time => Ok(TimeReference::Absolute(parse_string_literal(
            inner.as_str(),
        )?)),
        Rule::named_time => {
            let named = match inner.as_str() {
                "today" => NamedTime::Today,
                "yesterday" => NamedTime::Yesterday,
                "now" => NamedTime::Now,
                _ => {
                    return Err(ShapeError::ParseError {
                        message: format!("Unknown named time: {}", inner.as_str()),
                        location: None,
                    });
                }
            };
            Ok(TimeReference::Named(named))
        }
        Rule::relative_time => {
            // For now, store as string and parse later
            let s = inner.as_str();
            Ok(TimeReference::Relative(parse_relative_time(s)?))
        }
        _ => Err(ShapeError::ParseError {
            message: format!("Unexpected time reference: {:?}", inner.as_rule()),
            location: None,
        }),
    }
}

/// Parse relative time expression
pub fn parse_relative_time(s: &str) -> Result<RelativeTime> {
    // Simple parsing for now - this would be improved
    // Expected format: "1 week ago" or similar
    let parts: Vec<&str> = s.split_whitespace().collect();
    if parts.len() < 3 {
        return Err(ShapeError::ParseError {
            message: format!("Invalid relative time format: {}", s),
            location: None,
        });
    }

    let amount: i32 = parts[0].parse().map_err(|e| ShapeError::ParseError {
        message: format!("Invalid integer in relative time: {}", e),
        location: None,
    })?;
    let unit = match parts[1] {
        "minute" | "minutes" => TimeUnit::Minutes,
        "hour" | "hours" => TimeUnit::Hours,
        "day" | "days" => TimeUnit::Days,
        "week" | "weeks" => TimeUnit::Weeks,
        "month" | "months" => TimeUnit::Months,
        _ => {
            return Err(ShapeError::ParseError {
                message: format!("Unknown time unit: {}", parts[1]),
                location: None,
            });
        }
    };

    let direction = match parts[2] {
        "ago" => TimeDirection::Ago,
        "future" | "ahead" => TimeDirection::Future,
        _ => {
            return Err(ShapeError::ParseError {
                message: format!("Unknown time direction: {}", parts[2]),
                location: None,
            });
        }
    };

    Ok(RelativeTime {
        amount,
        unit,
        direction,
    })
}

/// Parse temporal navigation expression
/// Handles back(n) and forward(n) expressions
pub fn parse_temporal_nav(pair: Pair<Rule>) -> Result<Expr> {
    let span = pair_span(&pair);
    let inner = pair.into_inner().next().unwrap();

    match inner.as_rule() {
        Rule::back_nav | Rule::forward_nav => {
            let is_back = inner.as_rule() == Rule::back_nav;
            let nav_amount = inner.into_inner().next().unwrap();
            let mut amount_inner = nav_amount.into_inner();

            // Parse the number
            let num_pair = amount_inner.next().unwrap();
            let value: f64 = num_pair
                .as_str()
                .parse()
                .map_err(|e| ShapeError::ParseError {
                    message: format!("Invalid navigation amount: {}", e),
                    location: None,
                })?;

            // Parse optional time unit (defaults to samples)
            let unit = if let Some(unit_pair) = amount_inner.next() {
                match unit_pair.as_str() {
                    "sample" | "samples" | "record" | "records" => DurationUnit::Samples,
                    "minute" | "minutes" => DurationUnit::Minutes,
                    "hour" | "hours" => DurationUnit::Hours,
                    "day" | "days" => DurationUnit::Days,
                    "week" | "weeks" => DurationUnit::Weeks,
                    "month" | "months" => DurationUnit::Months,
                    _ => DurationUnit::Samples,
                }
            } else {
                DurationUnit::Samples
            };

            // For back navigation, negate the value
            let final_value = if is_back { -value } else { value };

            Ok(Expr::Duration(
                Duration {
                    value: final_value,
                    unit,
                },
                span,
            ))
        }
        _ => Err(ShapeError::ParseError {
            message: format!(
                "Expected back_nav or forward_nav, got {:?}",
                inner.as_rule()
            ),
            location: None,
        }),
    }
}

/// Parse timeframe expression
pub fn parse_timeframe_expr(pair: Pair<Rule>) -> Result<Expr> {
    let span = pair_span(&pair);
    let mut inner = pair.into_inner();

    // Parse the timeframe
    let timeframe_str = inner
        .next()
        .ok_or_else(|| ShapeError::ParseError {
            message: "Expected timeframe in on() expression".to_string(),
            location: None,
        })?
        .as_str();

    let timeframe = Timeframe::parse(timeframe_str).ok_or_else(|| ShapeError::ParseError {
        message: format!("Invalid timeframe: {}", timeframe_str),
        location: None,
    })?;

    // Parse the expression
    let expr_pair = inner.next().ok_or_else(|| ShapeError::ParseError {
        message: "Expected expression in on() block".to_string(),
        location: None,
    })?;

    let expr = crate::parser::expressions::parse_expression(expr_pair)?;

    Ok(Expr::TimeframeContext {
        timeframe,
        expr: Box::new(expr),
        span,
    })
}

/// Parse datetime expression
pub fn parse_datetime_expr(pair: Pair<Rule>) -> Result<DateTimeExpr> {
    match pair.as_rule() {
        Rule::datetime_expr => {
            // Delegate to inner rule
            let inner = pair.into_inner().next().unwrap();
            parse_datetime_expr(inner)
        }
        Rule::datetime_primary => {
            let mut inner = pair.into_inner();
            let expr_pair = inner.next().unwrap();

            match expr_pair.as_rule() {
                Rule::datetime_literal => {
                    let mut lit_inner = expr_pair.into_inner();
                    let string_pair = lit_inner.next().unwrap();
                    Ok(DateTimeExpr::Literal(parse_string_literal(
                        string_pair.as_str(),
                    )?))
                }
                Rule::named_time => {
                    let named = match expr_pair.as_str() {
                        "today" => NamedTime::Today,
                        "yesterday" => NamedTime::Yesterday,
                        "now" => NamedTime::Now,
                        _ => {
                            return Err(ShapeError::ParseError {
                                message: format!("Unknown named time: {}", expr_pair.as_str()),
                                location: None,
                            });
                        }
                    };
                    Ok(DateTimeExpr::Named(named))
                }
                _ => Err(ShapeError::ParseError {
                    message: format!("Unexpected datetime primary: {:?}", expr_pair.as_rule()),
                    location: None,
                }),
            }
        }
        Rule::datetime_arithmetic => {
            let mut inner = pair.into_inner();
            let base_pair = inner.next().unwrap();
            let mut result = parse_datetime_expr(base_pair)?;

            while let Some(op_pair) = inner.next() {
                let op = op_pair.as_str();
                if op != "+" && op != "-" {
                    return Err(ShapeError::ParseError {
                        message: format!("Invalid datetime arithmetic operator: {}", op),
                        location: None,
                    });
                }

                let duration_pair = inner.next().ok_or_else(|| ShapeError::ParseError {
                    message: "Datetime arithmetic missing duration".to_string(),
                    location: None,
                })?;
                let duration_expr = parse_duration(duration_pair)?;
                let duration = match duration_expr {
                    Expr::Duration(duration, _) => duration,
                    _ => {
                        return Err(ShapeError::ParseError {
                            message: "Datetime arithmetic expects a duration".to_string(),
                            location: None,
                        });
                    }
                };

                result = DateTimeExpr::Arithmetic {
                    base: Box::new(result),
                    operator: op.to_string(),
                    duration,
                };
            }

            Ok(result)
        }
        _ => Err(ShapeError::ParseError {
            message: format!("Unexpected datetime expression: {:?}", pair.as_rule()),
            location: None,
        }),
    }
}

/// Parse datetime range
pub fn parse_datetime_range(pair: Pair<Rule>) -> Result<(Expr, Option<Expr>)> {
    // Parse datetime_range: datetime_expr ("to" datetime_expr)?
    let mut inner = pair.into_inner();
    let first_pair = inner.next().unwrap();
    let first_span = pair_span(&first_pair);
    let first_datetime = parse_datetime_expr(first_pair)?;

    // Check if there's a "to" and second datetime
    if let Some(second_pair) = inner.next() {
        let second_span = pair_span(&second_pair);
        let second_datetime = parse_datetime_expr(second_pair)?;
        Ok((
            Expr::DateTime(first_datetime, first_span),
            Some(Expr::DateTime(second_datetime, second_span)),
        ))
    } else {
        Ok((Expr::DateTime(first_datetime, first_span), None))
    }
}

/// Parse duration expression
pub fn parse_duration(pair: Pair<Rule>) -> Result<Expr> {
    let span = pair_span(&pair);
    // Since duration is now atomic, parse the string directly
    let duration_str = pair.as_str();

    // Check if it's a compound duration (contains multiple units)
    let mut components = Vec::new();
    let mut current_number = String::new();
    let mut chars = duration_str.chars().peekable();

    while let Some(ch) = chars.next() {
        if ch.is_numeric() || ch == '.' || (ch == '-' && current_number.is_empty()) {
            current_number.push(ch);
        } else {
            // We've hit a unit character
            if !current_number.is_empty() {
                let value: f64 = current_number.parse().map_err(|e| ShapeError::ParseError {
                    message: format!("Invalid duration value: {}", e),
                    location: None,
                })?;

                // Collect the unit string
                let mut unit_str = String::new();
                unit_str.push(ch);

                // For long unit names like "minutes", "hours", etc.
                while let Some(&next_ch) = chars.peek() {
                    if next_ch.is_alphabetic() {
                        unit_str.push(chars.next().unwrap());
                    } else {
                        break;
                    }
                }

                let unit = match unit_str.as_str() {
                    "s" | "seconds" => DurationUnit::Seconds,
                    "m" | "minutes" => DurationUnit::Minutes,
                    "h" | "hours" => DurationUnit::Hours,
                    "d" | "days" => DurationUnit::Days,
                    "w" | "weeks" => DurationUnit::Weeks,
                    "M" | "months" => DurationUnit::Months,
                    "y" | "years" => DurationUnit::Years,
                    "samples" => DurationUnit::Samples,
                    _ => {
                        return Err(ShapeError::ParseError {
                            message: format!("Unknown duration unit: {}", unit_str),
                            location: None,
                        });
                    }
                };

                components.push((value, unit));
                current_number.clear();
            }
        }
    }

    // If there's only one component, return it directly
    if components.len() == 1 {
        let (value, unit) = components.into_iter().next().unwrap();
        return Ok(Expr::Duration(Duration { value, unit }, span));
    }

    // For compound durations, convert to seconds and find appropriate unit
    let mut total_seconds = 0.0;
    for (value, unit) in components {
        let seconds = match unit {
            DurationUnit::Seconds => value,
            DurationUnit::Minutes => value * 60.0,
            DurationUnit::Hours => value * 3600.0,
            DurationUnit::Days => value * 86400.0,
            DurationUnit::Weeks => value * 604800.0,
            DurationUnit::Months => value * 2592000.0, // Approximate: 30 days
            DurationUnit::Years => value * 31536000.0, // Approximate: 365 days
            DurationUnit::Samples => {
                return Err(ShapeError::ParseError {
                    message: "Cannot use 'samples' in compound duration".to_string(),
                    location: None,
                });
            }
        };
        total_seconds += seconds;
    }

    // Convert back to the most appropriate unit
    let (value, unit) = if total_seconds < 60.0 {
        (total_seconds, DurationUnit::Seconds)
    } else if total_seconds < 3600.0 {
        (total_seconds / 60.0, DurationUnit::Minutes)
    } else if total_seconds < 86400.0 {
        (total_seconds / 3600.0, DurationUnit::Hours)
    } else if total_seconds < 604800.0 {
        (total_seconds / 86400.0, DurationUnit::Days)
    } else if total_seconds < 2592000.0 {
        (total_seconds / 604800.0, DurationUnit::Weeks)
    } else if total_seconds < 31536000.0 {
        (total_seconds / 2592000.0, DurationUnit::Months)
    } else {
        (total_seconds / 31536000.0, DurationUnit::Years)
    };

    Ok(Expr::Duration(Duration { value, unit }, span))
}

#[cfg(test)]
mod tests {
    use crate::ast::{DateTimeExpr, DurationUnit, Expr};

    fn parse_expr(code: &str) -> Expr {
        let program = crate::parser::parse_program(code).expect("parse failed");
        // The last expression-statement's expr
        match &program.items[0] {
            crate::ast::Item::Expression(expr, _) => expr.clone(),
            crate::ast::Item::Statement(crate::ast::Statement::Expression(expr, _), _) => {
                expr.clone()
            }
            other => panic!("expected expression statement, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_datetime_literal_iso8601() {
        let expr = parse_expr(r#"@"2024-06-15T14:30:00""#);
        match expr {
            Expr::DateTime(DateTimeExpr::Literal(s), _) => {
                assert_eq!(s, "2024-06-15T14:30:00");
            }
            other => panic!("expected DateTime literal, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_datetime_literal_date_only() {
        let expr = parse_expr(r#"@"2024-01-15""#);
        match expr {
            Expr::DateTime(DateTimeExpr::Literal(s), _) => {
                assert_eq!(s, "2024-01-15");
            }
            other => panic!("expected DateTime literal, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_datetime_named_now() {
        let expr = parse_expr("@now");
        match expr {
            Expr::DateTime(DateTimeExpr::Named(crate::ast::NamedTime::Now), _) => {}
            other => panic!("expected DateTime Named(Now), got {:?}", other),
        }
    }

    #[test]
    fn test_parse_duration_days() {
        let expr = parse_expr("3d");
        match expr {
            Expr::Duration(dur, _) => {
                assert_eq!(dur.value, 3.0);
                assert_eq!(dur.unit, DurationUnit::Days);
            }
            other => panic!("expected Duration, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_duration_hours() {
        let expr = parse_expr("2h");
        match expr {
            Expr::Duration(dur, _) => {
                assert_eq!(dur.value, 2.0);
                assert_eq!(dur.unit, DurationUnit::Hours);
            }
            other => panic!("expected Duration, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_duration_minutes() {
        let expr = parse_expr("30m");
        match expr {
            Expr::Duration(dur, _) => {
                assert_eq!(dur.value, 30.0);
                assert_eq!(dur.unit, DurationUnit::Minutes);
            }
            other => panic!("expected Duration, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_duration_seconds() {
        let expr = parse_expr("10s");
        match expr {
            Expr::Duration(dur, _) => {
                assert_eq!(dur.value, 10.0);
                assert_eq!(dur.unit, DurationUnit::Seconds);
            }
            other => panic!("expected Duration, got {:?}", other),
        }
    }
}