ical-rs 0.5.1

iCalendar parser, validator, editor, merger and builder 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
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
//! # Validator
//!
//! The strict half of "liberal in, strict out", as a runtime predicate rather
//! than a second data model.
//!
//! Validity and lossiness are orthogonal: a conformant calendar may still
//! carry extensions (unknown components, properties, parameters and value
//! kinds), so "valid" cannot be a type with no `Unknown` arms.
//!
//! [`Ical::validate`] therefore walks the whole component tree and checks its
//! *known* parts against the per-property
//! [`IcalPropSpec`](crate::prop::spec::IcalPropSpec) and per-component
//! [`IcalComponentSpec`](crate::component::spec::IcalComponentSpec) for the
//! calendar version, leaving the unknown parts alone. It reports:
//!
//! - a property the version does not define;
//! - a value of a kind the property does not take;
//! - a parameter the property does not take;
//! - a property that appears more often than it may;
//! - a property a component requires but does not carry (a `VEVENT` needs `UID`
//!   and `DTSTAMP`, a `VALARM` needs `ACTION` and `TRIGGER`, ...);
//! - a component nested where it may not be;
//! - a recurrence rule that breaks RFC 5545 3.3.10.
//!
//! A passing check mints an [`IcalValid`] marker, the only way to obtain one,
//! so holding an `IcalValid<Ical>` is proof the check passed. The same
//! per-property check backs the [`IcalPropBuilder`]'s strict construction.
//!
//! [`IcalPropBuilder`]: crate::builder::IcalPropBuilder
//!
//! ## Example
//!
//! Decode a parsed calendar, validate it into a proof, and convert that back
//! into a byte tree:
//!
//! ```rust
//! # #[cfg(feature = "parser")] {
//! use ical::tree::cst::IcalCst;
//!
//! let raw = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//x//EN\r\nEND:VCALENDAR\r\n";
//! let cst = IcalCst::parse(raw).unwrap();
//!
//! // validate consumes the calendar and returns the proof (or the violations).
//! let valid = cst.decode().validate().expect("a conformant 2.0 calendar");
//!
//! // The proof converts back into a byte tree for free.
//! let out = IcalCst::from(valid);
//! assert!(out.to_string().contains("PRODID:-//x//EN"));
//! # }
//! ```

use core::{error, fmt, ops};

use alloc::{
    string::{String, ToString},
    vec::Vec,
};

use crate::{
    component::{IcalComponent, IcalComponentKind, IcalComponentName, spec::component_spec},
    ical::Ical,
    param::IcalParamKind,
    prop::{IcalProp, IcalPropKind, IcalPropName, spec::prop_spec},
    recur::validate::IcalRecurRuleProblem,
    value::IcalValueKind,
    version::IcalVersion,
};

/// A single conformance failure found by [`Ical::validate`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum IcalValidateError {
    /// A property appears in a version that does not define it.
    PropVersion {
        /// The offending property name.
        prop: String,
        /// The calendar version.
        version: IcalVersion,
    },
    /// A component is missing a property its spec requires.
    MissingProp {
        /// The component name.
        component: String,
        /// The required property name.
        prop: IcalPropKind,
    },
    /// A property carries a value of a kind its spec does not allow for the
    /// version.
    ValueKind {
        /// The offending property name.
        prop: IcalPropKind,
        /// The kind the value actually has.
        kind: IcalValueKind,
    },
    /// A property carries a known parameter its spec does not allow for the
    /// version. An extension parameter always passes.
    ParamNotAllowed {
        /// The offending property name.
        prop: IcalPropKind,
        /// The parameter that may not appear on it.
        param: IcalParamKind,
    },
    /// A property appears more times than its cardinality permits.
    ///
    /// Only the "too many" direction: absence is a
    /// [`MissingProp`](Self::MissingProp), since being required depends on the
    /// component a property sits in and the cardinality does not.
    TooMany {
        /// The component name.
        component: String,
        /// The repeated property.
        prop: IcalPropKind,
        /// How many times it appears.
        count: usize,
    },
    /// A component nests a child its spec does not allow.
    Nesting {
        /// The parent component name.
        parent: String,
        /// The child it may not hold.
        child: IcalComponentKind,
    },
    /// A recurrence rule breaks one of the RFC 5545 3.3.10 constraints.
    Rule {
        /// The property carrying the rule (`RRULE` or `EXRULE`).
        prop: IcalPropKind,
        /// What is wrong with it.
        problem: IcalRecurRuleProblem,
    },
}

impl fmt::Display for IcalValidateError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::PropVersion { prop, version } => {
                write!(
                    f,
                    "Property `{prop}` is not defined in version {}",
                    &**version
                )
            }
            Self::MissingProp { component, prop } => {
                write!(
                    f,
                    "Component `{component}` is missing required property `{}`",
                    &**prop
                )
            }
            Self::ValueKind { prop, kind } => {
                write!(
                    f,
                    "Property `{}` does not take a {} value",
                    &**prop, &**kind
                )
            }
            Self::ParamNotAllowed { prop, param } => {
                write!(
                    f,
                    "Property `{}` does not take the `{}` parameter",
                    &**prop, &**param
                )
            }
            Self::TooMany {
                component,
                prop,
                count,
            } => {
                write!(
                    f,
                    "Component `{component}` carries property `{}` {count} times",
                    &**prop
                )
            }
            Self::Nesting { parent, child } => {
                write!(
                    f,
                    "Component `{parent}` does not nest a `{}` component",
                    &**child
                )
            }
            Self::Rule { prop, problem } => {
                write!(
                    f,
                    "Property `{}` carries an invalid rule: {problem}",
                    &**prop
                )
            }
        }
    }
}

impl error::Error for IcalValidateError {}

impl Ical<'_> {
    /// Validate the whole calendar, returning an [`IcalValid`] proof or every
    /// conformance failure found.
    pub fn validate(self) -> Result<IcalValid<Self>, Vec<IcalValidateError>> {
        let mut errors = Vec::new();

        for prop in &self.props {
            validate_prop(prop, self.version, &mut errors);
        }
        // NOTE: The calendar envelope requires PRODID (VERSION is the
        // hoisted-out indicator, always present in the model).
        check_required(
            IcalComponentKind::VCalendar,
            "VCALENDAR",
            &self.props,
            &mut errors,
        );

        for component in &self.components {
            validate_component(component, self.version, &mut errors);
        }

        if errors.is_empty() {
            Ok(IcalValid(self))
        } else {
            Err(errors)
        }
    }
}

/// Validate one component (recursively): its properties, its required-property
/// set, how many times each property appears, what it nests, and its nested
/// components.
fn validate_component(
    component: &IcalComponent<'_>,
    version: IcalVersion,
    errors: &mut Vec<IcalValidateError>,
) {
    for prop in &component.props {
        validate_prop(prop, version, errors);
    }

    check_cardinality(&component.name, &component.props, version, errors);

    if let IcalComponentName::Kind(kind) = component.name {
        check_required(kind, &component.name, &component.props, errors);
        check_nesting(kind, &component.name, &component.components, errors);
    }

    for child in &component.components {
        validate_component(child, version, errors);
    }
}

/// Push a [`MissingProp`](IcalValidateError::MissingProp) for every property a
/// component of `kind` requires but does not carry.
fn check_required(
    kind: IcalComponentKind,
    name: &str,
    props: &[IcalProp<'_>],
    errors: &mut Vec<IcalValidateError>,
) {
    for &required in (component_spec(kind).required_props)() {
        let present = props
            .iter()
            .any(|prop| matches!(prop.name, IcalPropName::Kind(k) if k == required));
        if !present {
            errors.push(IcalValidateError::MissingProp {
                component: name.to_string(),
                prop: required,
            });
        }
    }
}

/// The per-property check, shared by [`Ical::validate`] and the
/// [builder](crate::builder).
///
/// Unknown (extension) properties, parameters and value kinds always pass:
/// validity is a runtime predicate over the *known* vocabulary, and an
/// extension is outside it by definition.
///
/// A known property must exist in the calendar's version, take a value of a
/// kind its spec allows there, and carry only parameters that spec allows
/// there. A recurrence value is checked against RFC 5545 3.3.10 as well.
pub(crate) fn validate_prop(
    prop: &IcalProp<'_>,
    version: IcalVersion,
    errors: &mut Vec<IcalValidateError>,
) {
    let IcalPropName::Kind(kind) = prop.name else {
        return;
    };

    let spec = prop_spec(kind);

    if !(spec.allowed_versions)().contains(&version) {
        errors.push(IcalValidateError::PropVersion {
            prop: (*kind).to_string(),
            version,
        });
    }

    if let Some(value) = prop.value.kind()
        && !(spec.allowed_values)(version).contains(&value)
    {
        errors.push(IcalValidateError::ValueKind {
            prop: kind,
            kind: value,
        });
    }

    let allowed_params = (spec.allowed_params)(version);
    for param in &prop.params {
        if let Some(param) = param.kind()
            && !allowed_params.contains(&param)
        {
            errors.push(IcalValidateError::ParamNotAllowed { prop: kind, param });
        }
    }

    validate_rule(kind, prop, errors);
}

/// Check the rule a `RRULE` or `EXRULE` carries against RFC 5545 3.3.10.
///
/// A rule the typed layer cannot even read is left alone: parsing is liberal,
/// and an unreadable rule is a parse-level fact, not a conformance one.
fn validate_rule(kind: IcalPropKind, prop: &IcalProp<'_>, errors: &mut Vec<IcalValidateError>) {
    use crate::{recur::IcalRecurRule, value::IcalValue};

    if !matches!(kind, IcalPropKind::RRule | IcalPropKind::ExRule) {
        return;
    }

    let IcalValue::Recur(recur) = &prop.value else {
        return;
    };

    let Ok(rule) = IcalRecurRule::parse(&recur.0) else {
        return;
    };

    errors.extend(
        rule.problems()
            .into_iter()
            .map(|problem| IcalValidateError::Rule {
                prop: kind,
                problem,
            }),
    );
}

/// Report a [`TooMany`](IcalValidateError::TooMany) per over-frequent property.
///
/// Only the "too many" direction: whether a property is *required* depends on
/// the component it sits in, which the per-property cardinality does not know,
/// so absence stays [`check_required`]'s job.
fn check_cardinality(
    name: &str,
    props: &[IcalProp<'_>],
    version: IcalVersion,
    errors: &mut Vec<IcalValidateError>,
) {
    use crate::prop::cardinality::IcalPropCardinality::{AtMostOne, ExactlyOne};

    let mut seen: Vec<(IcalPropKind, usize)> = Vec::new();

    for prop in props {
        let IcalPropName::Kind(kind) = prop.name else {
            continue;
        };

        match seen.iter_mut().find(|(held, _)| *held == kind) {
            Some((_, count)) => *count += 1,
            None => seen.push((kind, 1)),
        }
    }

    for (kind, count) in seen {
        if count > 1
            && matches!(
                (prop_spec(kind).cardinality)(version),
                ExactlyOne | AtMostOne
            )
        {
            errors.push(IcalValidateError::TooMany {
                component: name.to_string(),
                prop: kind,
                count,
            });
        }
    }
}

/// Push a [`Nesting`](IcalValidateError::Nesting) for every child a component
/// may not hold. An unknown child component always passes.
fn check_nesting(
    kind: IcalComponentKind,
    name: &str,
    children: &[IcalComponent<'_>],
    errors: &mut Vec<IcalValidateError>,
) {
    let allowed = (component_spec(kind).allowed_children)();

    for child in children {
        if let IcalComponentName::Kind(child_kind) = child.name
            && !allowed.contains(&child_kind)
        {
            errors.push(IcalValidateError::Nesting {
                parent: name.to_string(),
                child: child_kind,
            });
        }
    }
}

/// A value that passed its validator. Only a validator can mint one, so
/// holding it is proof of conformance.
///
/// Two validators mint it, at opposite ends of the crate: [`Ical::validate`]
/// over a whole calendar, and
/// [`IcalRecurRule::validate`](crate::recur::IcalRecurRule::validate) over one
/// recurrence rule.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct IcalValid<T>(pub(crate) T);

impl<T> IcalValid<T> {
    /// Unwrap the validated value.
    pub fn into_inner(self) -> T {
        self.0
    }
}

impl<T> ops::Deref for IcalValid<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<'a> TryFrom<Ical<'a>> for IcalValid<Ical<'a>> {
    type Error = Vec<IcalValidateError>;

    fn try_from(cal: Ical<'a>) -> Result<Self, Self::Error> {
        cal.validate()
    }
}

#[cfg(test)]
mod tests {
    use alloc::vec;

    use crate::{
        component::{IcalComponent, IcalComponentKind},
        ical::Ical,
        param::IcalParamKind,
        prop::{IcalProp, IcalPropKind},
        validator::IcalValidateError,
        value::{IcalValue, IcalValueKind, datetime::IcalDateTime, text::IcalText},
        version::IcalVersion,
    };

    fn prop(kind: IcalPropKind, value: IcalValue<'static>) -> IcalProp<'static> {
        IcalProp {
            name: kind.into(),
            params: vec![],
            value,
        }
    }

    #[test]
    fn accepts_a_conformant_calendar() {
        let cal = Ical {
            version: IcalVersion::V2_0,
            props: vec![prop(
                IcalPropKind::ProdId,
                IcalValue::Text(IcalText("-//x//EN".into())),
            )],
            components: vec![IcalComponent {
                name: IcalComponentKind::VEvent.into(),
                props: vec![
                    prop(IcalPropKind::Uid, IcalValue::Text(IcalText("1".into()))),
                    prop(
                        IcalPropKind::DtStamp,
                        IcalValue::DateTime(IcalDateTime("20260101T000000Z".into())),
                    ),
                ],
                components: vec![],
            }],
        };
        assert!(cal.validate().is_ok());
    }

    #[test]
    fn flags_a_component_missing_a_required_property() {
        let cal = Ical {
            version: IcalVersion::V2_0,
            props: vec![prop(
                IcalPropKind::ProdId,
                IcalValue::Text(IcalText("-//x//EN".into())),
            )],
            components: vec![IcalComponent {
                name: IcalComponentKind::VEvent.into(),
                props: vec![],
                components: vec![],
            }],
        };
        let errors = cal.validate().unwrap_err();
        assert_eq!(errors.len(), 2);
    }

    /// A conformant calendar wrapping one `VEVENT` built from `props`.
    fn around(props: vec::Vec<IcalProp<'static>>) -> Ical<'static> {
        let mut event = vec![
            prop(IcalPropKind::Uid, IcalValue::Text(IcalText("1".into()))),
            prop(
                IcalPropKind::DtStamp,
                IcalValue::DateTime(IcalDateTime("20260101T000000Z".into())),
            ),
        ];
        event.extend(props);

        Ical {
            version: IcalVersion::V2_0,
            props: vec![prop(
                IcalPropKind::ProdId,
                IcalValue::Text(IcalText("-//x//EN".into())),
            )],
            components: vec![IcalComponent {
                name: IcalComponentKind::VEvent.into(),
                props: event,
                components: vec![],
            }],
        }
    }

    #[test]
    fn flags_a_value_of_the_wrong_kind() {
        let cal = around(vec![prop(
            IcalPropKind::Summary,
            IcalValue::DateTime(IcalDateTime("20260101T000000Z".into())),
        )]);

        assert_eq!(
            cal.validate().unwrap_err(),
            [IcalValidateError::ValueKind {
                prop: IcalPropKind::Summary,
                kind: IcalValueKind::DateTime,
            }]
        );
    }

    #[test]
    fn passes_an_extension_value_kind() {
        // NOTE: An unknown value has no kind to check, so it cannot be the
        // wrong one.
        let cal = around(vec![IcalProp {
            name: "X-THING".into(),
            params: vec![],
            value: IcalValue::DateTime(IcalDateTime("20260101T000000Z".into())),
        }]);

        assert!(cal.validate().is_ok());
    }

    #[test]
    fn flags_a_parameter_the_property_does_not_take() {
        use crate::param::IcalParam;

        let cal = around(vec![IcalProp {
            name: IcalPropKind::Summary.into(),
            params: vec![IcalParam::PartStat("ACCEPTED".into())],
            value: IcalValue::Text(IcalText("Lunch".into())),
        }]);

        assert_eq!(
            cal.validate().unwrap_err(),
            [IcalValidateError::ParamNotAllowed {
                prop: IcalPropKind::Summary,
                param: IcalParamKind::PartStat,
            }]
        );
    }

    #[test]
    fn passes_an_extension_parameter() {
        use crate::param::IcalParam;

        let cal = around(vec![IcalProp {
            name: IcalPropKind::Summary.into(),
            params: vec![IcalParam::Unknown {
                name: "X-THING".into(),
                values: vec!["1".into()],
            }],
            value: IcalValue::Text(IcalText("Lunch".into())),
        }]);

        assert!(cal.validate().is_ok());
    }

    #[test]
    fn flags_a_single_valued_property_that_repeats() {
        let cal = around(vec![
            prop(IcalPropKind::Summary, IcalValue::Text(IcalText("a".into()))),
            prop(IcalPropKind::Summary, IcalValue::Text(IcalText("b".into()))),
        ]);

        assert_eq!(
            cal.validate().unwrap_err(),
            [IcalValidateError::TooMany {
                component: "VEVENT".into(),
                prop: IcalPropKind::Summary,
                count: 2,
            }]
        );
    }

    #[test]
    fn passes_a_repeatable_property_that_repeats() {
        let cal = around(vec![
            prop(
                IcalPropKind::Comment,
                IcalValue::Text(IcalText("one".into())),
            ),
            prop(
                IcalPropKind::Comment,
                IcalValue::Text(IcalText("two".into())),
            ),
        ]);

        assert!(cal.validate().is_ok());
    }

    #[test]
    fn flags_a_component_nested_where_it_may_not_be() {
        let mut cal = around(vec![]);
        cal.components[0].components.push(IcalComponent {
            name: IcalComponentKind::VTimezone.into(),
            props: vec![prop(
                IcalPropKind::TzId,
                IcalValue::Text(IcalText("Europe/Paris".into())),
            )],
            components: vec![],
        });

        let errors = cal.validate().unwrap_err();
        assert!(errors.contains(&IcalValidateError::Nesting {
            parent: "VEVENT".into(),
            child: IcalComponentKind::VTimezone,
        }));
    }

    #[test]
    fn passes_an_extension_component() {
        let mut cal = around(vec![]);
        cal.components[0].components.push(IcalComponent {
            name: "X-THING".into(),
            props: vec![],
            components: vec![],
        });

        assert!(cal.validate().is_ok());
    }

    #[test]
    fn flags_a_rule_the_rfc_forbids() {
        use crate::{
            recur::{IcalRecurFreq, validate::IcalRecurPart, validate::IcalRecurRuleProblem},
            value::recur::IcalRecur,
        };

        let cal = around(vec![prop(
            IcalPropKind::RRule,
            IcalValue::Recur(IcalRecur("FREQ=MONTHLY;BYWEEKNO=3".into())),
        )]);

        assert_eq!(
            cal.validate().unwrap_err(),
            [IcalValidateError::Rule {
                prop: IcalPropKind::RRule,
                problem: IcalRecurRuleProblem::PartFreq {
                    part: IcalRecurPart::ByWeekNo,
                    freq: IcalRecurFreq::Monthly,
                },
            }]
        );
    }
}