rd-rds 0.5.0

Read-only reader for the subset of R's RDS serialization format used by installed-package help databases
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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
//! Typed access to declarations stored in `Meta/nsInfo.rds`.
//!
//! These declarations describe namespace metadata written from a package's
//! `NAMESPACE`; they are not a runtime export set, a set of stored lazy-load
//! bindings, or the result of evaluating export patterns. In particular, this
//! view does not resolve regular expressions, synthesize S4 exports into
//! regular exports, or inspect `.onLoad` behavior.

use std::fmt;

use super::{
    InstalledMetadataError, ValueKindName, ViewError, decode_optional, decode_required,
    expect_list, invalid_dimensions, named_values, unexpected_length, unexpected_type,
};
use crate::{RObject, RStr, RValue};

/// The state of one known namespace metadata field.
///
/// `Missing` means that the field was absent from the metadata object.
/// `Present` includes an empty collection. `Invalid` means the field belongs
/// to the supported schema but contains invalid data. `UnsupportedSchema`
/// means that the shape was understood but is outside the supported profile.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum MetadataField<T> {
    Missing,
    Present(T),
    Invalid(ViewError),
    UnsupportedSchema { description: String },
}

impl<T> MetadataField<T> {
    /// Borrows a present value while preserving the field state.
    pub fn as_ref(&self) -> MetadataField<&T> {
        match self {
            Self::Missing => MetadataField::Missing,
            Self::Present(value) => MetadataField::Present(value),
            Self::Invalid(error) => MetadataField::Invalid(error.clone()),
            Self::UnsupportedSchema { description } => MetadataField::UnsupportedSchema {
                description: description.clone(),
            },
        }
    }

    /// Returns the owned value when the field is present and valid.
    pub fn present(&self) -> Option<&T> {
        match self {
            Self::Present(value) => Some(value),
            Self::Missing | Self::Invalid(_) | Self::UnsupportedSchema { .. } => None,
        }
    }
}

/// One imported binding, retaining the source name and local alias.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImportedName {
    source_name: String,
    local_name: String,
}

/// One statically declared export, retaining source and exported names.
///
/// For an ordinary `export(name)` declaration both names are identical. An
/// assignment-shaped declaration such as `export(public_name = internal_name)`
/// retains the source binding as `source_name` and the namespace binding as
/// `exported_name`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NamespaceExport {
    source_name: String,
    exported_name: String,
}

impl NamespaceExport {
    /// Creates an exported source/binding name pair.
    pub fn new(source_name: impl Into<String>, exported_name: impl Into<String>) -> Self {
        Self {
            source_name: source_name.into(),
            exported_name: exported_name.into(),
        }
    }

    /// Returns the source binding name.
    pub fn source_name(&self) -> &str {
        &self.source_name
    }

    /// Returns the name exposed by the namespace.
    pub fn exported_name(&self) -> &str {
        &self.exported_name
    }
}

impl ImportedName {
    /// Creates an imported source/local name pair.
    pub fn new(source_name: impl Into<String>, local_name: impl Into<String>) -> Self {
        Self {
            source_name: source_name.into(),
            local_name: local_name.into(),
        }
    }

    /// Returns the name exported by the source package.
    pub fn source_name(&self) -> &str {
        &self.source_name
    }

    /// Returns the name bound in the importing package.
    pub fn local_name(&self) -> &str {
        &self.local_name
    }
}

/// One declaration from a namespace `import` or `importFrom` directive.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NamespaceImport {
    /// Import all exports from `package`, except the listed names.
    All {
        package: String,
        except: Vec<String>,
    },
    /// Import selected names from `package`, retaining local aliases.
    From {
        package: String,
        names: Vec<ImportedName>,
    },
}

impl NamespaceImport {
    /// Returns the source package name.
    pub fn package(&self) -> &str {
        match self {
            Self::All { package, .. } | Self::From { package, .. } => package,
        }
    }
}

/// Whether an S3 registration has an explicit function name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum S3MethodName {
    /// The registration has an `NA` function column.
    Implicit,
    /// The registration names a function explicitly.
    Explicit(String),
}

/// One row from the supported four-column S3 registration matrix.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct S3Registration {
    generic: String,
    class: String,
    method: S3MethodName,
    generic_package: Option<String>,
}

impl S3Registration {
    pub fn generic(&self) -> &str {
        &self.generic
    }

    pub fn class(&self) -> &str {
        &self.class
    }

    pub fn method(&self) -> &S3MethodName {
        &self.method
    }

    pub fn generic_package(&self) -> Option<&str> {
        self.generic_package.as_deref()
    }
}

/// Owned typed declarations from an installed package's `Meta/nsInfo.rds`.
///
/// The fields are independent: an invalid S3 matrix does not prevent valid
/// declared exports from being read. The declarations are retained in input
/// order and duplicates are not removed. They describe static namespace
/// declarations only; they do not promise runtime exports, stored bindings,
/// regex evaluation, re-exports, or `.onLoad` additions.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NamespaceMetadata {
    declared_exports: MetadataField<Vec<NamespaceExport>>,
    export_patterns: MetadataField<Vec<String>>,
    imports: MetadataField<Vec<NamespaceImport>>,
    s3_registrations: MetadataField<Vec<S3Registration>>,
    s3_generic_evidence: MetadataField<Vec<String>>,
    export_classes: MetadataField<Vec<String>>,
    export_methods: MetadataField<Vec<String>>,
    export_class_patterns: MetadataField<Vec<String>>,
}

impl NamespaceMetadata {
    /// Reads and validates `Meta/nsInfo.rds` below an installed package
    /// directory.
    pub fn read_installed(
        package_dir: impl AsRef<std::path::Path>,
    ) -> Result<Self, InstalledMetadataError> {
        Self::read_installed_with_options(package_dir, &crate::file::ReadOptions::default())
    }

    /// Reads and validates `Meta/nsInfo.rds` with explicit file and decode
    /// bounds.
    pub fn read_installed_with_options(
        package_dir: impl AsRef<std::path::Path>,
        options: &crate::file::ReadOptions,
    ) -> Result<Self, InstalledMetadataError> {
        let (path, object) = super::read_installed_object(package_dir, "nsInfo.rds", options)?;
        Self::from_object(&object).map_err(|source| InstalledMetadataError::View { path, source })
    }

    /// Parses an owned view of a named `Meta/nsInfo.rds` list.
    ///
    /// The root must be a named list. Unknown fields are ignored. Duplicate
    /// known fields make only that field `Invalid`, allowing other fields to
    /// remain useful to callers.
    pub fn from_object(object: &RObject) -> Result<Self, ViewError> {
        let items = expect_list(object, "NamespaceMetadata", None)?;
        let names = named_values(object, "NamespaceMetadata", None)?;
        if names.len() != items.len() {
            return Err(unexpected_length(
                "NamespaceMetadata",
                None,
                items.len().to_string(),
                names.len(),
            ));
        }

        let mut fields = Vec::with_capacity(items.len());
        for (index, name) in names.iter().enumerate() {
            let name = decode_required(name, &format!("NamespaceMetadata[{index}]"), None)?;
            fields.push((name, &items[index]));
        }

        Ok(Self {
            declared_exports: parse_known_field(&fields, "exports", parse_exports),
            export_patterns: parse_known_field(&fields, "exportPatterns", parse_strings),
            imports: parse_known_field(&fields, "imports", parse_imports),
            s3_registrations: parse_known_field(&fields, "S3methods", parse_s3_registrations),
            s3_generic_evidence: parse_known_field(&fields, "S3methods", parse_s3_generic_evidence),
            export_classes: parse_known_field(&fields, "exportClasses", parse_strings),
            export_methods: parse_known_field(&fields, "exportMethods", parse_strings),
            export_class_patterns: parse_known_field(&fields, "exportClassPatterns", parse_strings),
        })
    }

    pub fn declared_exports(&self) -> &MetadataField<Vec<NamespaceExport>> {
        &self.declared_exports
    }

    pub fn export_patterns(&self) -> &MetadataField<Vec<String>> {
        &self.export_patterns
    }

    pub fn imports(&self) -> &MetadataField<Vec<NamespaceImport>> {
        &self.imports
    }

    pub fn s3_registrations(&self) -> &MetadataField<Vec<S3Registration>> {
        &self.s3_registrations
    }

    pub fn s3_generic_evidence(&self) -> &MetadataField<Vec<String>> {
        &self.s3_generic_evidence
    }

    pub fn export_classes(&self) -> &MetadataField<Vec<String>> {
        &self.export_classes
    }

    pub fn export_methods(&self) -> &MetadataField<Vec<String>> {
        &self.export_methods
    }

    pub fn export_class_patterns(&self) -> &MetadataField<Vec<String>> {
        &self.export_class_patterns
    }
}

impl TryFrom<&RObject> for NamespaceMetadata {
    type Error = ViewError;

    fn try_from(value: &RObject) -> Result<Self, Self::Error> {
        Self::from_object(value)
    }
}

enum ParseFailure {
    Invalid(ViewError),
    Unsupported(String),
}

fn parse_known_field<T, F>(fields: &[(String, &RObject)], name: &str, parser: F) -> MetadataField<T>
where
    F: FnOnce(&RObject, &str) -> Result<T, ParseFailure>,
{
    let mut matches = fields.iter().filter(|(field, _)| field == name);
    let Some((_, object)) = matches.next() else {
        return MetadataField::Missing;
    };
    if matches.next().is_some() {
        return MetadataField::Invalid(super::duplicate(
            &format!("NamespaceMetadata.{name}"),
            Some(name.to_owned()),
        ));
    }
    match parser(object, &format!("NamespaceMetadata.{name}")) {
        Ok(value) => MetadataField::Present(value),
        Err(ParseFailure::Invalid(error)) => MetadataField::Invalid(error),
        Err(ParseFailure::Unsupported(description)) => {
            MetadataField::UnsupportedSchema { description }
        }
    }
}

fn parse_exports(object: &RObject, path: &str) -> Result<Vec<NamespaceExport>, ParseFailure> {
    let values = match object.value() {
        RValue::Character(values) => values,
        value => {
            return Err(ParseFailure::Invalid(unexpected_type(
                path,
                None,
                "character vector",
                value.kind_name(),
            )));
        }
    };
    let aliases = match object.attributes().get("names") {
        None => None,
        Some(attribute) => match &attribute.value() {
            RValue::Character(names) => Some(names),
            value => {
                return Err(ParseFailure::Invalid(unexpected_type(
                    &format!("{path}.names"),
                    None,
                    "character vector",
                    value.kind_name(),
                )));
            }
        },
    };
    if let Some(aliases) = aliases
        && aliases.len() != values.len()
    {
        return Err(ParseFailure::Invalid(unexpected_length(
            &format!("{path}.names"),
            None,
            values.len().to_string(),
            aliases.len(),
        )));
    }
    values
        .iter()
        .enumerate()
        .map(|(index, value)| {
            let source_name = decode_required(value, &format!("{path}[{index}]"), None)
                .map_err(ParseFailure::Invalid)?;
            let exported_name = match aliases {
                Some(aliases) => {
                    let alias =
                        decode_required(&aliases[index], &format!("{path}.names[{index}]"), None)
                            .map_err(ParseFailure::Invalid)?;
                    if alias.is_empty() {
                        source_name.clone()
                    } else {
                        alias
                    }
                }
                None => source_name.clone(),
            };
            Ok(NamespaceExport {
                source_name,
                exported_name,
            })
        })
        .collect()
}

fn parse_strings(object: &RObject, path: &str) -> Result<Vec<String>, ParseFailure> {
    let values = match object.value() {
        RValue::Character(values) => values,
        value => {
            return Err(ParseFailure::Invalid(unexpected_type(
                path,
                None,
                "character vector",
                value.kind_name(),
            )));
        }
    };
    values
        .iter()
        .enumerate()
        .map(|(index, value)| {
            decode_required(value, &format!("{path}[{index}]"), None).map_err(ParseFailure::Invalid)
        })
        .collect()
}

fn parse_imports(object: &RObject, path: &str) -> Result<Vec<NamespaceImport>, ParseFailure> {
    match object.value() {
        RValue::Character(values) => values
            .iter()
            .enumerate()
            .map(|(index, value)| {
                let package = decode_required(value, &format!("{path}[{index}]"), None)
                    .map_err(ParseFailure::Invalid)?;
                Ok(NamespaceImport::All {
                    package,
                    except: Vec::new(),
                })
            })
            .collect(),
        RValue::List(values) => values
            .iter()
            .enumerate()
            .map(|(index, value)| parse_import_entry(value, &format!("{path}[{index}]")))
            .collect(),
        value => Err(ParseFailure::Invalid(unexpected_type(
            path,
            None,
            "character vector or list",
            value.kind_name(),
        ))),
    }
}

fn parse_import_entry(object: &RObject, path: &str) -> Result<NamespaceImport, ParseFailure> {
    if let RValue::Character(values) = object.value() {
        if values.len() != 1 {
            return Err(ParseFailure::Invalid(unexpected_length(
                path,
                None,
                "1".to_owned(),
                values.len(),
            )));
        }
        return Ok(NamespaceImport::All {
            package: decode_required(&values[0], path, None).map_err(ParseFailure::Invalid)?,
            except: Vec::new(),
        });
    }

    let RValue::List(values) = object.value() else {
        return Err(ParseFailure::Unsupported(format!(
            "{path} is not a supported import declaration"
        )));
    };
    let names = match object.attributes().get("names") {
        Some(attribute) => match &attribute.value() {
            RValue::Character(names) => Some(names),
            value => {
                return Err(ParseFailure::Invalid(unexpected_type(
                    &format!("{path}.names"),
                    None,
                    "character vector",
                    value.kind_name(),
                )));
            }
        },
        None => None,
    };
    let Some(names) = names else {
        // The only observed unnamed shape is list(package, selections).
        if values.len() != 2 {
            return Err(ParseFailure::Unsupported(format!(
                "{path} does not contain a supported positional import declaration"
            )));
        }
        let package = parse_package_scalar(&values[0], &format!("{path}[0]"))?;
        let selections = parse_imported_names(&values[1], &format!("{path}[1]"))?;
        return Ok(NamespaceImport::From {
            package,
            names: selections,
        });
    };

    if names.len() != values.len() {
        return Err(ParseFailure::Invalid(unexpected_length(
            &format!("{path}.names"),
            None,
            values.len().to_string(),
            names.len(),
        )));
    }

    // A named entry must be interpreted entirely by its names. In particular,
    // an unknown second name must not silently turn a two-element list into
    // the positional package/selections shape. R writes the package element
    // of `list("pkg", except = ...)` with an empty name; only that first
    // position is accepted as an implicit package field.
    let mut decoded_names = Vec::with_capacity(names.len());
    let mut empty_name_indices = Vec::new();
    for (index, name) in names.iter().enumerate() {
        let decoded = decode_required(name, &format!("{path}.names[{index}]"), None)
            .map_err(ParseFailure::Invalid)?;
        if decoded.is_empty() {
            empty_name_indices.push(index);
            decoded_names.push(decoded);
            continue;
        }
        if !matches!(
            decoded.as_str(),
            "package" | "except" | "selections" | "names"
        ) {
            return Err(ParseFailure::Unsupported(format!(
                "{path} contains unsupported import field {decoded:?}"
            )));
        }
        if decoded_names.iter().any(|existing| existing == &decoded) {
            return Err(ParseFailure::Invalid(super::duplicate(
                &format!("{path}.names"),
                Some(decoded),
            )));
        }
        decoded_names.push(decoded);
    }

    if empty_name_indices != [0] && !empty_name_indices.is_empty() {
        return Err(ParseFailure::Unsupported(format!(
            "{path} has an unnamed import field outside the first position"
        )));
    }
    let named_package_index = decoded_names.iter().position(|name| name == "package");
    if !empty_name_indices.is_empty() && named_package_index.is_some() {
        return Err(ParseFailure::Invalid(super::duplicate(
            &format!("{path}.names"),
            Some("package".into()),
        )));
    }
    let package_index = empty_name_indices.first().copied().or(named_package_index);
    let Some(package_index) = package_index else {
        return Err(ParseFailure::Unsupported(format!(
            "{path} does not contain a package entry"
        )));
    };
    let package =
        parse_package_scalar(&values[package_index], &format!("{path}[{package_index}]"))?;

    let except_index = decoded_names.iter().position(|name| name == "except");
    let selection_indices: Vec<_> = decoded_names
        .iter()
        .enumerate()
        .filter_map(|(index, name)| {
            matches!(name.as_str(), "selections" | "names").then_some(index)
        })
        .collect();
    if selection_indices.len() > 1 {
        return Err(ParseFailure::Invalid(unexpected_type(
            &format!("{path}.names"),
            None,
            "one import selection field",
            "multiple import selection fields",
        )));
    }
    if except_index.is_some() && !selection_indices.is_empty() {
        return Err(ParseFailure::Invalid(unexpected_type(
            &format!("{path}.names"),
            None,
            "either except or selections/names",
            "both except and selections/names",
        )));
    }
    if let Some(except_index) = except_index {
        let except =
            parse_string_vector(&values[except_index], &format!("{path}[{except_index}]"))?;
        return Ok(NamespaceImport::All { package, except });
    }

    let Some(selection_index) = selection_indices.first().copied() else {
        return Err(ParseFailure::Unsupported(format!(
            "{path} does not contain import selections or except"
        )));
    };
    let selections = parse_imported_names(
        &values[selection_index],
        &format!("{path}[{selection_index}]"),
    )?;
    Ok(NamespaceImport::From {
        package,
        names: selections,
    })
}

fn parse_package_scalar(object: &RObject, path: &str) -> Result<String, ParseFailure> {
    let RValue::Character(values) = object.value() else {
        return Err(ParseFailure::Invalid(unexpected_type(
            path,
            None,
            "character scalar",
            object.value().kind_name(),
        )));
    };
    if values.len() != 1 {
        return Err(ParseFailure::Invalid(unexpected_length(
            path,
            None,
            "1".to_owned(),
            values.len(),
        )));
    }
    decode_required(&values[0], path, None).map_err(ParseFailure::Invalid)
}

fn parse_string_vector(object: &RObject, path: &str) -> Result<Vec<String>, ParseFailure> {
    parse_strings(object, path)
}

fn parse_imported_names(object: &RObject, path: &str) -> Result<Vec<ImportedName>, ParseFailure> {
    let RValue::Character(values) = object.value() else {
        return Err(ParseFailure::Invalid(unexpected_type(
            path,
            None,
            "character vector",
            object.value().kind_name(),
        )));
    };
    let aliases = match object.attributes().get("names") {
        None => None,
        Some(attribute) => match &attribute.value() {
            RValue::Character(values) => Some(values),
            value => {
                return Err(ParseFailure::Invalid(unexpected_type(
                    &format!("{path}.names"),
                    None,
                    "character vector",
                    value.kind_name(),
                )));
            }
        },
    };
    if let Some(aliases) = aliases
        && aliases.len() != values.len()
    {
        return Err(ParseFailure::Invalid(unexpected_length(
            &format!("{path}.names"),
            None,
            values.len().to_string(),
            aliases.len(),
        )));
    }
    values
        .iter()
        .enumerate()
        .map(|(index, value)| {
            let source_name = decode_required(value, &format!("{path}[{index}]"), None)
                .map_err(ParseFailure::Invalid)?;
            let local_name = match aliases {
                Some(aliases) => {
                    let alias =
                        decode_required(&aliases[index], &format!("{path}.names[{index}]"), None)
                            .map_err(ParseFailure::Invalid)?;
                    if alias.is_empty() {
                        source_name.clone()
                    } else {
                        alias
                    }
                }
                None => source_name.clone(),
            };
            Ok(ImportedName {
                source_name,
                local_name,
            })
        })
        .collect()
}

fn parse_s3_registrations(
    object: &RObject,
    path: &str,
) -> Result<Vec<S3Registration>, ParseFailure> {
    let matrix = parse_character_matrix(object, path)?;
    if matrix.ncol == 0 {
        return Err(ParseFailure::Invalid(invalid_dimensions(
            path,
            "S3 registration matrix must have at least one column",
        )));
    }
    if matrix.ncol != 4 {
        return Err(ParseFailure::Unsupported(format!(
            "S3 registration matrix has {} columns; only the four-column schema is supported",
            matrix.ncol
        )));
    }
    (0..matrix.nrow)
        .map(|row| {
            let generic = matrix.required(row, 0, path)?;
            let class = matrix.required(row, 1, path)?;
            let method = match matrix.optional(row, 2, path)? {
                Some(value) => S3MethodName::Explicit(value),
                None => S3MethodName::Implicit,
            };
            let generic_package = matrix.optional(row, 3, path)?;
            Ok(S3Registration {
                generic,
                class,
                method,
                generic_package,
            })
        })
        .collect()
}

fn parse_s3_generic_evidence(object: &RObject, path: &str) -> Result<Vec<String>, ParseFailure> {
    let matrix = parse_character_matrix(object, path)?;
    if matrix.ncol == 0 {
        return Err(ParseFailure::Invalid(invalid_dimensions(
            path,
            "S3 metadata matrix must have at least one column",
        )));
    }
    (0..matrix.nrow)
        .map(|row| matrix.required(row, 0, path))
        .collect()
}

struct CharacterMatrix<'a> {
    values: &'a [RStr],
    nrow: usize,
    ncol: usize,
}

impl CharacterMatrix<'_> {
    fn at(&self, row: usize, column: usize) -> &RStr {
        &self.values[row + column * self.nrow]
    }

    fn required(&self, row: usize, column: usize, path: &str) -> Result<String, ParseFailure> {
        decode_required(
            self.at(row, column),
            &format!("{path}[row={row},column={column}]"),
            None,
        )
        .map_err(ParseFailure::Invalid)
    }

    fn optional(
        &self,
        row: usize,
        column: usize,
        path: &str,
    ) -> Result<Option<String>, ParseFailure> {
        decode_optional(
            self.at(row, column),
            &format!("{path}[row={row},column={column}]"),
            None,
        )
        .map_err(ParseFailure::Invalid)
    }
}

fn parse_character_matrix<'a>(
    object: &'a RObject,
    path: &str,
) -> Result<CharacterMatrix<'a>, ParseFailure> {
    let values = match object.value() {
        RValue::Character(values) => values,
        value => {
            return Err(ParseFailure::Invalid(unexpected_type(
                path,
                None,
                "character matrix",
                value.kind_name(),
            )));
        }
    };
    let dimensions = object.attributes().get("dim").ok_or_else(|| {
        ParseFailure::Invalid(super::missing(format!("{path}.attributes.dim"), None))
    })?;
    let RValue::Integer(dimensions) = dimensions.value() else {
        return Err(ParseFailure::Invalid(unexpected_type(
            &format!("{path}.attributes.dim"),
            None,
            "integer vector",
            dimensions.value().kind_name(),
        )));
    };
    if dimensions.len() != 2 {
        return Err(ParseFailure::Invalid(unexpected_length(
            &format!("{path}.attributes.dim"),
            None,
            "2".to_owned(),
            dimensions.len(),
        )));
    }
    let mut shape = [0usize; 2];
    for (index, value) in dimensions.iter().enumerate() {
        let Some(value) = value else {
            return Err(ParseFailure::Invalid(invalid_dimensions(
                &format!("{path}.attributes.dim"),
                "dimensions must not contain NA",
            )));
        };
        if *value < 0 {
            return Err(ParseFailure::Invalid(invalid_dimensions(
                &format!("{path}.attributes.dim"),
                "dimensions must not be negative",
            )));
        }
        shape[index] = *value as usize;
    }
    let expected = shape[0].checked_mul(shape[1]).ok_or_else(|| {
        ParseFailure::Invalid(invalid_dimensions(
            &format!("{path}.attributes.dim"),
            "dimension product overflows",
        ))
    })?;
    if expected != values.len() {
        return Err(ParseFailure::Invalid(unexpected_length(
            path,
            None,
            expected.to_string(),
            values.len(),
        )));
    }
    Ok(CharacterMatrix {
        values,
        nrow: shape[0],
        ncol: shape[1],
    })
}

impl fmt::Display for S3MethodName {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Implicit => formatter.write_str("implicit"),
            Self::Explicit(value) => formatter.write_str(value),
        }
    }
}