Skip to main content

r_description/
scalar.rs

1//! Scalar `DESCRIPTION` field accessors.
2
3use crate::{FieldMutationError, RDescription, Spanned};
4
5macro_rules! required_string_field {
6    ($error:ident, $method:ident, $field:literal, $description:literal) => {
7        #[doc = concat!("Errors returned by [`RDescription::", stringify!($method), "`].")]
8        #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
9        pub enum $error {
10            #[doc = concat!("The required `", $field, "` field is absent.")]
11            #[error("required {field} field is missing", field = $field)]
12            Missing,
13
14            #[doc = concat!("The `", $field, "` field occurs more than once.")]
15            #[error("{field} field is declared multiple times", field = $field)]
16            Duplicate(Vec<Spanned<String>>),
17        }
18
19        impl $error {
20            #[doc = concat!("Returns the duplicate `", $field, "` occurrences, if present.")]
21            pub fn occurrences(&self) -> &[Spanned<String>] {
22                match self {
23                    Self::Missing => &[],
24                    Self::Duplicate(occurrences) => occurrences,
25                }
26            }
27        }
28
29        impl RDescription {
30            #[doc = $description]
31            #[doc = concat!("\n\nThe field is matched ASCII case-insensitively and must occur exactly once across all recovered paragraphs. The returned string is its logical DCF value and may contain newlines.")]
32            pub fn $method(&self) -> Result<String, $error> {
33                let values = self.field_values($field);
34                match values.as_slice() {
35                    [] => Err($error::Missing),
36                    [value] => Ok(value.value().clone()),
37                    _ => Err($error::Duplicate(values)),
38                }
39            }
40        }
41    };
42}
43
44macro_rules! optional_string_field {
45    ($error:ident, $method:ident, $field:literal, $description:literal) => {
46        #[doc = concat!("Errors returned by [`RDescription::", stringify!($method), "`].")]
47        #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
48        pub enum $error {
49            #[doc = concat!("The `", $field, "` field occurs more than once.")]
50            #[error("{field} field is declared multiple times", field = $field)]
51            Duplicate(Vec<Spanned<String>>),
52        }
53
54        impl $error {
55            #[doc = concat!("Returns the duplicate `", $field, "` occurrences.")]
56            pub fn occurrences(&self) -> &[Spanned<String>] {
57                match self {
58                    Self::Duplicate(occurrences) => occurrences,
59                }
60            }
61        }
62
63        impl RDescription {
64            #[doc = $description]
65            #[doc = concat!("\n\nThe field is matched ASCII case-insensitively and may occur at most once across all recovered paragraphs. The returned string is its logical DCF value and may contain newlines.")]
66            pub fn $method(&self) -> Result<Option<String>, $error> {
67                let values = self.field_values($field);
68                match values.as_slice() {
69                    [] => Ok(None),
70                    [value] => Ok(Some(value.value().clone())),
71                    _ => Err($error::Duplicate(values)),
72                }
73            }
74        }
75    };
76}
77
78macro_rules! optional_logical_field {
79    ($error:ident, $method:ident, $field:literal, $description:literal) => {
80        #[doc = concat!("Errors returned by [`RDescription::", stringify!($method), "`].")]
81        #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
82        pub enum $error {
83            #[doc = concat!("The `", $field, "` field occurs more than once.")]
84            #[error("{field} field is declared multiple times", field = $field)]
85            Duplicate(Vec<Spanned<String>>),
86
87            #[doc = concat!("The `", $field, "` value is not a supported logical value.")]
88            #[error("invalid logical value for {field}", field = $field)]
89            Invalid(Spanned<String>),
90        }
91
92        impl $error {
93            #[doc = concat!("Returns the values responsible for the `", $field, "` error.")]
94            pub fn occurrences(&self) -> &[Spanned<String>] {
95                match self {
96                    Self::Duplicate(occurrences) => occurrences,
97                    Self::Invalid(value) => std::slice::from_ref(value),
98                }
99            }
100        }
101
102        impl RDescription {
103            #[doc = $description]
104            #[doc = concat!("\n\nThe field name is matched ASCII case-insensitively. Its optional value accepts `yes`, `true`, `no`, or `false` case-insensitively and may occur at most once.")]
105            pub fn $method(&self) -> Result<Option<bool>, $error> {
106                let values = self.field_values($field);
107                match values.as_slice() {
108                    [] => Ok(None),
109                    [value] => parse_logical(value.value())
110                        .map(Some)
111                        .ok_or_else(|| $error::Invalid(value.clone())),
112                    _ => Err($error::Duplicate(values)),
113                }
114            }
115        }
116    };
117}
118
119fn parse_logical(value: &str) -> Option<bool> {
120    if value.eq_ignore_ascii_case("yes") || value.eq_ignore_ascii_case("true") {
121        Some(true)
122    } else if value.eq_ignore_ascii_case("no") || value.eq_ignore_ascii_case("false") {
123        Some(false)
124    } else {
125        None
126    }
127}
128
129macro_rules! required_string_mutation {
130    ($setter:ident, $field:literal) => {
131        impl RDescription {
132            #[doc = concat!("Sets the required `", $field, "` field to a single-line value.")]
133            #[doc = "\n\nThe first case-insensitive occurrence is replaced using canonical field-name spelling and later occurrences are removed. Use `set_field` to intentionally write multiline values."]
134            #[doc = "\n\n# Errors\n\nReturns `FieldMutationError` without changing the document if the value contains a line break or begins with a space or tab."]
135            pub fn $setter(&mut self, value: &str) -> Result<(), FieldMutationError> {
136                self.set_scalar_field($field, value)
137            }
138        }
139    };
140}
141
142macro_rules! optional_string_mutation {
143    ($setter:ident, $remover:ident, $field:literal) => {
144        impl RDescription {
145            #[doc = concat!("Sets the optional `", $field, "` field to a single-line value.")]
146            #[doc = "\n\nThe first case-insensitive occurrence is replaced using canonical field-name spelling and later occurrences are removed. Use `set_field` to intentionally write multiline values."]
147            #[doc = "\n\n# Errors\n\nReturns `FieldMutationError` without changing the document if the value contains a line break or begins with a space or tab."]
148            pub fn $setter(&mut self, value: &str) -> Result<(), FieldMutationError> {
149                self.set_scalar_field($field, value)
150            }
151
152            #[doc = concat!("Removes every occurrence of the optional `", $field, "` field.")]
153            pub fn $remover(&mut self) {
154                self.remove_field($field);
155            }
156        }
157    };
158}
159
160macro_rules! optional_logical_mutation {
161    ($setter:ident, $remover:ident, $field:literal) => {
162        impl RDescription {
163            #[doc = concat!("Sets the optional `", $field, "` field using canonical `yes` or `no` spelling.")]
164            #[doc = "\n\nThe first case-insensitive occurrence is replaced using canonical field-name spelling and later occurrences are removed."]
165            pub fn $setter(&mut self, value: bool) {
166                self.set_known_single_line_field($field, if value { "yes" } else { "no" });
167            }
168
169            #[doc = concat!("Removes every occurrence of the optional `", $field, "` field.")]
170            pub fn $remover(&mut self) {
171                self.remove_field($field);
172            }
173        }
174    };
175}
176
177required_string_field!(
178    PackageError,
179    package,
180    "Package",
181    "Returns the package name without enforcing R's package-name style guidelines."
182);
183required_string_field!(TitleError, title, "Title", "Returns the package title.");
184required_string_field!(
185    DescriptionError,
186    description,
187    "Description",
188    "Returns the package description."
189);
190required_string_field!(
191    LicenseError,
192    license,
193    "License",
194    "Returns the package license declaration without interpreting its license grammar."
195);
196
197optional_string_field!(
198    AuthorsAtRError,
199    authors_at_r,
200    "Authors@R",
201    "Returns the package's `Authors@R` expression as text."
202);
203optional_string_field!(
204    AuthorError,
205    author,
206    "Author",
207    "Returns the package author text."
208);
209optional_string_field!(
210    MaintainerError,
211    maintainer,
212    "Maintainer",
213    "Returns the package maintainer text."
214);
215optional_string_field!(
216    CopyrightError,
217    copyright,
218    "Copyright",
219    "Returns the package copyright declaration."
220);
221optional_string_field!(
222    DateError,
223    date,
224    "Date",
225    "Returns the package release date as text."
226);
227optional_string_field!(
228    EncodingError,
229    encoding,
230    "Encoding",
231    "Returns the declared source encoding."
232);
233optional_string_field!(
234    SystemRequirementsError,
235    system_requirements,
236    "SystemRequirements",
237    "Returns external system requirements as uninterpreted text."
238);
239optional_string_field!(
240    BugReportsError,
241    bug_reports,
242    "BugReports",
243    "Returns the bug-report destination as text."
244);
245optional_string_field!(
246    PriorityError,
247    priority,
248    "Priority",
249    "Returns the package priority as text."
250);
251optional_string_field!(
252    OsTypeError,
253    os_type,
254    "OS_type",
255    "Returns the supported operating-system type as text."
256);
257optional_string_field!(
258    PackageTypeError,
259    package_type,
260    "Type",
261    "Returns the package type as text."
262);
263optional_string_field!(
264    RepositoryError,
265    repository,
266    "Repository",
267    "Returns repository metadata as text."
268);
269optional_string_field!(
270    ContactError,
271    contact,
272    "Contact",
273    "Returns the package contact information as text."
274);
275optional_string_field!(
276    MailingListError,
277    mailing_list,
278    "MailingList",
279    "Returns the package mailing-list information as text."
280);
281optional_string_field!(
282    NoteError,
283    note,
284    "Note",
285    "Returns package or repository notes as text."
286);
287
288optional_logical_field!(
289    LazyDataError,
290    lazy_data,
291    "LazyData",
292    "Returns whether package datasets use lazy loading."
293);
294optional_logical_field!(
295    LazyLoadError,
296    lazy_load,
297    "LazyLoad",
298    "Returns the deprecated lazy-loading setting."
299);
300optional_logical_field!(
301    KeepSourceError,
302    keep_source,
303    "KeepSource",
304    "Returns whether package code should retain source text."
305);
306optional_logical_field!(
307    ByteCompileError,
308    byte_compile,
309    "ByteCompile",
310    "Returns whether package R code should be byte-compiled."
311);
312optional_logical_field!(
313    UseLtoError,
314    use_lto,
315    "UseLTO",
316    "Returns whether package native code should use link-time optimization."
317);
318optional_logical_field!(
319    StagedInstallError,
320    staged_install,
321    "StagedInstall",
322    "Returns whether package installation should be staged."
323);
324optional_logical_field!(
325    ZipDataError,
326    zip_data,
327    "ZipData",
328    "Returns the ignored legacy data-compression setting."
329);
330optional_logical_field!(
331    BiarchError,
332    biarch,
333    "Biarch",
334    "Returns the Windows bi-architecture installation setting."
335);
336optional_logical_field!(
337    BuildVignettesError,
338    build_vignettes,
339    "BuildVignettes",
340    "Returns whether package vignettes should be built."
341);
342optional_logical_field!(
343    NeedsCompilationError,
344    needs_compilation,
345    "NeedsCompilation",
346    "Returns whether the package needs native compilation."
347);
348optional_logical_field!(
349    LicenseIsFossError,
350    license_is_foss,
351    "License_is_FOSS",
352    "Returns repository metadata indicating whether the package license is free or open source."
353);
354optional_logical_field!(
355    LicenseRestrictsUseError,
356    license_restricts_use,
357    "License_restricts_use",
358    "Returns repository metadata indicating whether the package license restricts use."
359);
360
361required_string_mutation!(set_package, "Package");
362required_string_mutation!(set_title, "Title");
363required_string_mutation!(set_description, "Description");
364required_string_mutation!(set_license, "License");
365
366optional_string_mutation!(set_authors_at_r, remove_authors_at_r, "Authors@R");
367optional_string_mutation!(set_author, remove_author, "Author");
368optional_string_mutation!(set_maintainer, remove_maintainer, "Maintainer");
369optional_string_mutation!(set_copyright, remove_copyright, "Copyright");
370optional_string_mutation!(set_date, remove_date, "Date");
371optional_string_mutation!(set_encoding, remove_encoding, "Encoding");
372optional_string_mutation!(
373    set_system_requirements,
374    remove_system_requirements,
375    "SystemRequirements"
376);
377optional_string_mutation!(set_bug_reports, remove_bug_reports, "BugReports");
378optional_string_mutation!(set_priority, remove_priority, "Priority");
379optional_string_mutation!(set_os_type, remove_os_type, "OS_type");
380optional_string_mutation!(set_package_type, remove_package_type, "Type");
381optional_string_mutation!(set_repository, remove_repository, "Repository");
382optional_string_mutation!(set_contact, remove_contact, "Contact");
383optional_string_mutation!(set_mailing_list, remove_mailing_list, "MailingList");
384optional_string_mutation!(set_note, remove_note, "Note");
385
386optional_logical_mutation!(set_lazy_data, remove_lazy_data, "LazyData");
387optional_logical_mutation!(set_lazy_load, remove_lazy_load, "LazyLoad");
388optional_logical_mutation!(set_keep_source, remove_keep_source, "KeepSource");
389optional_logical_mutation!(set_byte_compile, remove_byte_compile, "ByteCompile");
390optional_logical_mutation!(set_use_lto, remove_use_lto, "UseLTO");
391optional_logical_mutation!(set_staged_install, remove_staged_install, "StagedInstall");
392optional_logical_mutation!(set_zip_data, remove_zip_data, "ZipData");
393optional_logical_mutation!(set_biarch, remove_biarch, "Biarch");
394optional_logical_mutation!(
395    set_build_vignettes,
396    remove_build_vignettes,
397    "BuildVignettes"
398);
399optional_logical_mutation!(
400    set_needs_compilation,
401    remove_needs_compilation,
402    "NeedsCompilation"
403);
404optional_logical_mutation!(
405    set_license_is_foss,
406    remove_license_is_foss,
407    "License_is_FOSS"
408);
409optional_logical_mutation!(
410    set_license_restricts_use,
411    remove_license_restricts_use,
412    "License_restricts_use"
413);
414
415#[cfg(test)]
416mod tests {
417    use super::*;
418
419    #[test]
420    fn required_scalar_is_explicitly_missing() {
421        assert_eq!(
422            RDescription::parse("").package(),
423            Err(PackageError::Missing)
424        );
425    }
426
427    #[test]
428    fn package_name_is_not_style_validated() {
429        let description = RDescription::parse("Package: 1 wonky package.\n");
430        assert_eq!(description.package().as_deref(), Ok("1 wonky package."));
431    }
432
433    #[test]
434    fn scalar_duplicates_across_paragraphs_are_errors() {
435        let description = RDescription::parse("Package: first\n\nPackage: second\n");
436        let PackageError::Duplicate(occurrences) = description.package().unwrap_err() else {
437            panic!("expected duplicate Package error");
438        };
439
440        assert_eq!(occurrences.len(), 2);
441        assert_eq!(occurrences[0].value(), "first");
442        assert_eq!(occurrences[1].value(), "second");
443    }
444
445    #[test]
446    fn optional_scalar_distinguishes_absence_and_duplicates() {
447        assert_eq!(RDescription::parse("").encoding(), Ok(None));
448
449        let description = RDescription::parse("Encoding: UTF-8\n\nEncoding: latin1\n");
450        assert!(matches!(
451            description.encoding(),
452            Err(EncodingError::Duplicate(values)) if values.len() == 2
453        ));
454    }
455
456    #[test]
457    fn logical_fields_accept_r_spellings_case_insensitively() {
458        for (value, expected) in [
459            ("yes", true),
460            ("TRUE", true),
461            ("No", false),
462            ("false", false),
463        ] {
464            let description = RDescription::parse(&format!("LazyData: {value}\n"));
465            assert_eq!(description.lazy_data(), Ok(Some(expected)));
466        }
467    }
468
469    #[test]
470    fn invalid_logical_value_retains_its_source_range() {
471        let input = "LazyData: perhaps\n";
472        let description = RDescription::parse(input);
473        let LazyDataError::Invalid(value) = description.lazy_data().unwrap_err() else {
474            panic!("expected invalid LazyData error");
475        };
476
477        assert_eq!(value.value(), "perhaps");
478        assert_eq!(
479            &input[usize::from(value.range().start())..usize::from(value.range().end())],
480            "perhaps"
481        );
482    }
483
484    #[test]
485    fn all_scalar_accessors_use_their_expected_fields() {
486        let description = RDescription::parse(
487            "Package: pkg\nTitle: title\nDescription: description\nLicense: MIT\n\
488             Authors@R: person('A')\nAuthor: A\nMaintainer: A <a@example.com>\n\
489             Copyright: A\nDate: 2026-08-15\nEncoding: UTF-8\n\
490             SystemRequirements: make\nBugReports: mailto:a@example.com\n\
491             Priority: recommended\nOS_type: unix\nType: Package\nRepository: CRAN\n\
492             Contact: Team\nMailingList: list@example.com\nNote: note\n\
493             LazyData: yes\nLazyLoad: no\nKeepSource: true\nByteCompile: false\n\
494             UseLTO: yes\nStagedInstall: no\nZipData: true\nBiarch: false\n\
495             BuildVignettes: yes\nNeedsCompilation: no\nLicense_is_FOSS: yes\n\
496             License_restricts_use: no\n",
497        );
498
499        assert_eq!(description.package().as_deref(), Ok("pkg"));
500        assert_eq!(description.title().as_deref(), Ok("title"));
501        assert_eq!(description.description().as_deref(), Ok("description"));
502        assert_eq!(description.license().as_deref(), Ok("MIT"));
503        assert_eq!(
504            description.authors_at_r().unwrap().as_deref(),
505            Some("person('A')")
506        );
507        assert_eq!(description.author().unwrap().as_deref(), Some("A"));
508        assert_eq!(
509            description.maintainer().unwrap().as_deref(),
510            Some("A <a@example.com>")
511        );
512        assert_eq!(description.copyright().unwrap().as_deref(), Some("A"));
513        assert_eq!(description.date().unwrap().as_deref(), Some("2026-08-15"));
514        assert_eq!(description.encoding().unwrap().as_deref(), Some("UTF-8"));
515        assert_eq!(
516            description.system_requirements().unwrap().as_deref(),
517            Some("make")
518        );
519        assert_eq!(
520            description.bug_reports().unwrap().as_deref(),
521            Some("mailto:a@example.com")
522        );
523        assert_eq!(
524            description.priority().unwrap().as_deref(),
525            Some("recommended")
526        );
527        assert_eq!(description.os_type().unwrap().as_deref(), Some("unix"));
528        assert_eq!(
529            description.package_type().unwrap().as_deref(),
530            Some("Package")
531        );
532        assert_eq!(description.repository().unwrap().as_deref(), Some("CRAN"));
533        assert_eq!(description.contact().unwrap().as_deref(), Some("Team"));
534        assert_eq!(
535            description.mailing_list().unwrap().as_deref(),
536            Some("list@example.com")
537        );
538        assert_eq!(description.note().unwrap().as_deref(), Some("note"));
539        assert_eq!(description.lazy_data(), Ok(Some(true)));
540        assert_eq!(description.lazy_load(), Ok(Some(false)));
541        assert_eq!(description.keep_source(), Ok(Some(true)));
542        assert_eq!(description.byte_compile(), Ok(Some(false)));
543        assert_eq!(description.use_lto(), Ok(Some(true)));
544        assert_eq!(description.staged_install(), Ok(Some(false)));
545        assert_eq!(description.zip_data(), Ok(Some(true)));
546        assert_eq!(description.biarch(), Ok(Some(false)));
547        assert_eq!(description.build_vignettes(), Ok(Some(true)));
548        assert_eq!(description.needs_compilation(), Ok(Some(false)));
549        assert_eq!(description.license_is_foss(), Ok(Some(true)));
550        assert_eq!(description.license_restricts_use(), Ok(Some(false)));
551    }
552
553    #[test]
554    fn named_scalar_setters_use_expected_fields_and_canonical_logicals() {
555        let mut description = RDescription::parse("");
556
557        description.set_package("pkg").unwrap();
558        description.set_title("title").unwrap();
559        description.set_description("description").unwrap();
560        description.set_license("MIT").unwrap();
561        description.set_authors_at_r("person('A')").unwrap();
562        description.set_author("A").unwrap();
563        description.set_maintainer("A <a@example.com>").unwrap();
564        description.set_copyright("A").unwrap();
565        description.set_date("2026-08-15").unwrap();
566        description.set_encoding("UTF-8").unwrap();
567        description.set_system_requirements("make").unwrap();
568        description.set_bug_reports("mailto:a@example.com").unwrap();
569        description.set_priority("recommended").unwrap();
570        description.set_os_type("unix").unwrap();
571        description.set_package_type("Package").unwrap();
572        description.set_repository("CRAN").unwrap();
573        description.set_contact("Team").unwrap();
574        description.set_mailing_list("list@example.com").unwrap();
575        description.set_note("note").unwrap();
576        description.set_lazy_data(true);
577        description.set_lazy_load(false);
578        description.set_keep_source(true);
579        description.set_byte_compile(false);
580        description.set_use_lto(true);
581        description.set_staged_install(false);
582        description.set_zip_data(true);
583        description.set_biarch(false);
584        description.set_build_vignettes(true);
585        description.set_needs_compilation(false);
586        description.set_license_is_foss(true);
587        description.set_license_restricts_use(false);
588
589        for (field, expected) in [
590            ("Package", "pkg"),
591            ("Title", "title"),
592            ("Description", "description"),
593            ("License", "MIT"),
594            ("Authors@R", "person('A')"),
595            ("Author", "A"),
596            ("Maintainer", "A <a@example.com>"),
597            ("Copyright", "A"),
598            ("Date", "2026-08-15"),
599            ("Encoding", "UTF-8"),
600            ("SystemRequirements", "make"),
601            ("BugReports", "mailto:a@example.com"),
602            ("Priority", "recommended"),
603            ("OS_type", "unix"),
604            ("Type", "Package"),
605            ("Repository", "CRAN"),
606            ("Contact", "Team"),
607            ("MailingList", "list@example.com"),
608            ("Note", "note"),
609            ("LazyData", "yes"),
610            ("LazyLoad", "no"),
611            ("KeepSource", "yes"),
612            ("ByteCompile", "no"),
613            ("UseLTO", "yes"),
614            ("StagedInstall", "no"),
615            ("ZipData", "yes"),
616            ("Biarch", "no"),
617            ("BuildVignettes", "yes"),
618            ("NeedsCompilation", "no"),
619            ("License_is_FOSS", "yes"),
620            ("License_restricts_use", "no"),
621        ] {
622            let values = description.field_values(field);
623            assert_eq!(values.len(), 1, "unexpected {field} cardinality");
624            assert_eq!(values[0].value(), expected, "wrong {field} value");
625        }
626
627        assert_eq!(description.package().as_deref(), Ok("pkg"));
628        assert_eq!(
629            description.authors_at_r().unwrap().as_deref(),
630            Some("person('A')")
631        );
632        assert_eq!(description.note().unwrap().as_deref(), Some("note"));
633        assert_eq!(description.lazy_data(), Ok(Some(true)));
634        assert_eq!(description.license_restricts_use(), Ok(Some(false)));
635        assert!(description.to_string().contains("LazyData: yes\n"));
636        assert!(description
637            .to_string()
638            .contains("License_restricts_use: no\n"));
639    }
640
641    #[test]
642    fn optional_removers_clear_all_occurrences() {
643        let mut description =
644            RDescription::parse("Author: first\nLazyData: yes\n\nAuthor: second\nLazyData: no\n");
645
646        description.remove_author();
647        description.remove_lazy_data();
648
649        assert_eq!(description.author(), Ok(None));
650        assert_eq!(description.lazy_data(), Ok(None));
651    }
652
653    #[test]
654    fn named_scalar_setters_reject_multiline_values() {
655        let mut description = RDescription::parse("Description: original\n");
656        assert_eq!(
657            description.set_description("first\nsecond"),
658            Err(FieldMutationError::MultilineScalar {
659                field: "Description"
660            })
661        );
662        assert_eq!(description.description().as_deref(), Ok("original"));
663
664        description
665            .set_field("Description", "first\nsecond")
666            .unwrap();
667        assert_eq!(description.description().as_deref(), Ok("first\nsecond"));
668    }
669
670    #[test]
671    fn named_scalar_setters_reject_leading_dcf_indentation() {
672        let mut description = RDescription::parse("Title: original\n");
673        assert_eq!(
674            description.set_title("  changed"),
675            Err(FieldMutationError::LeadingWhitespace { line: 1 })
676        );
677        assert_eq!(description.title().as_deref(), Ok("original"));
678    }
679}