Skip to main content

r_packages/
validation.rs

1use std::fmt;
2
3use r_dcf_syntax::{DiagnosticKind, SourceSpan};
4use r_metadata::RelationList;
5
6use crate::Packages;
7
8/// A stable category of syntax or package-record validation finding.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10pub enum FindingKind {
11    /// A field line has no colon.
12    MalformedField,
13    /// A continuation has no preceding field.
14    OrphanContinuation,
15    /// A DCF field name is invalid.
16    InvalidFieldName,
17    /// A required `Package` field is absent.
18    MissingPackage,
19    /// A required `Version` field is absent.
20    MissingVersion,
21    /// A scalar field occurs more than once.
22    DuplicateScalarField,
23    /// A `Package` value is not a valid package name.
24    InvalidPackageName,
25    /// A `Version` value is not a valid package version.
26    InvalidVersion,
27    /// A logical field has an unknown value.
28    InvalidLogical,
29    /// A `Priority` value is unknown.
30    InvalidPriority,
31    /// An `OS_type` value is unknown.
32    InvalidOsType,
33    /// A package relation contains invalid syntax.
34    InvalidRelation,
35}
36
37/// One record-indexed validation finding and its document byte span.
38#[derive(Debug, Clone, PartialEq, Eq, Hash)]
39pub struct Finding {
40    kind: FindingKind,
41    record_index: usize,
42    span: SourceSpan,
43    field_name: Option<String>,
44}
45
46impl Finding {
47    /// Returns the stable finding category.
48    pub const fn kind(&self) -> FindingKind {
49        self.kind
50    }
51
52    /// Returns the zero-based record index.
53    pub const fn record_index(&self) -> usize {
54        self.record_index
55    }
56
57    /// Returns the document-relative byte span.
58    pub const fn span(&self) -> SourceSpan {
59        self.span
60    }
61
62    /// Returns the related case-sensitive field name, when applicable.
63    pub fn field_name(&self) -> Option<&str> {
64        self.field_name.as_deref()
65    }
66
67    /// Returns a stable human-readable description.
68    pub const fn message(&self) -> &'static str {
69        match self.kind {
70            FindingKind::MalformedField => "field line is missing a colon",
71            FindingKind::OrphanContinuation => "continuation line has no preceding field",
72            FindingKind::InvalidFieldName => "invalid field name",
73            FindingKind::MissingPackage => "required Package field is missing",
74            FindingKind::MissingVersion => "required Version field is missing",
75            FindingKind::DuplicateScalarField => "scalar field is duplicated",
76            FindingKind::InvalidPackageName => "invalid package name",
77            FindingKind::InvalidVersion => "invalid package version",
78            FindingKind::InvalidLogical => "invalid logical value",
79            FindingKind::InvalidPriority => "invalid package priority",
80            FindingKind::InvalidOsType => "invalid OS type",
81            FindingKind::InvalidRelation => "invalid package relation",
82        }
83    }
84}
85
86impl fmt::Display for Finding {
87    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
88        write!(
89            formatter,
90            "record {}: {} at {}..{}",
91            self.record_index,
92            self.message(),
93            self.span.start,
94            self.span.end
95        )
96    }
97}
98
99const RELATION_FIELDS: &[&str] = &["Depends", "Imports", "Suggests", "Enhances", "LinkingTo"];
100const LOGICAL_FIELDS: &[&str] = &[
101    "NeedsCompilation",
102    "License_is_FOSS",
103    "License_restricts_use",
104    "ByteCompile",
105    "KeepSource",
106];
107const NON_SCALAR_FIELDS: &[&str] = RELATION_FIELDS;
108
109impl Packages {
110    /// Validates syntax and field-local repository metadata in source order.
111    ///
112    /// This performs no CRAN policy checks. Every finding is independent, so a
113    /// malformed value in one field does not prevent validation of neighbours.
114    pub fn validate(&self) -> Vec<Finding> {
115        let records = self.parse.records().collect::<Vec<_>>();
116        let mut findings = Vec::new();
117
118        for diagnostic in self.parse.diagnostics() {
119            let record_index = record_for_span(&records, diagnostic.span());
120            findings.push(Finding {
121                kind: match diagnostic.kind() {
122                    DiagnosticKind::MalformedField => FindingKind::MalformedField,
123                    DiagnosticKind::OrphanContinuation => FindingKind::OrphanContinuation,
124                    DiagnosticKind::InvalidFieldName => FindingKind::InvalidFieldName,
125                },
126                record_index,
127                span: diagnostic.span(),
128                field_name: None,
129            });
130        }
131
132        for (record_index, record) in records.iter().enumerate() {
133            let point = SourceSpan::new(record.source_range().start, record.source_range().start);
134            for (name, kind) in [
135                ("Package", FindingKind::MissingPackage),
136                ("Version", FindingKind::MissingVersion),
137            ] {
138                if record.last_field(name).is_none() {
139                    findings.push(finding(kind, record_index, point, Some(name)));
140                }
141            }
142
143            let fields = record.fields().collect::<Vec<_>>();
144            for (position, field) in fields.iter().enumerate() {
145                let Some(name) = field.name() else { continue };
146                let value = field.value();
147                if !NON_SCALAR_FIELDS.contains(&name.as_str())
148                    && fields[..position]
149                        .iter()
150                        .any(|previous| previous.name().as_deref() == Some(name.as_str()))
151                {
152                    findings.push(finding(
153                        FindingKind::DuplicateScalarField,
154                        record_index,
155                        field.source_range(),
156                        Some(&name),
157                    ));
158                }
159                validate_value(&mut findings, record_index, &name, &value);
160            }
161        }
162        findings.sort_by_key(|item| (item.span.start, item.span.end, item.kind as u8));
163        findings
164    }
165}
166
167fn validate_value(
168    findings: &mut Vec<Finding>,
169    record_index: usize,
170    name: &str,
171    value: &r_dcf_syntax::ValueText,
172) {
173    let span = value.source_range();
174    let invalid = match name {
175        "Package" if !valid_package_name(value.as_str()) => Some(FindingKind::InvalidPackageName),
176        "Version" if value.as_str().parse::<r_metadata::Version>().is_err() => {
177            Some(FindingKind::InvalidVersion)
178        }
179        "Priority" if value.as_str().parse::<r_metadata::Priority>().is_err() => {
180            Some(FindingKind::InvalidPriority)
181        }
182        "OS_type" if value.as_str().parse::<r_metadata::OsType>().is_err() => {
183            Some(FindingKind::InvalidOsType)
184        }
185        name if LOGICAL_FIELDS.contains(&name)
186            && value.as_str().parse::<r_metadata::Logical>().is_err() =>
187        {
188            Some(FindingKind::InvalidLogical)
189        }
190        _ => None,
191    };
192    if let Some(kind) = invalid {
193        findings.push(finding(kind, record_index, span, Some(name)));
194    }
195    if RELATION_FIELDS.contains(&name) {
196        for issue in RelationList::parse(value.as_str()).issues() {
197            let relative = issue.span();
198            findings.push(finding(
199                FindingKind::InvalidRelation,
200                record_index,
201                SourceSpan::new(span.start + relative.start(), span.start + relative.end()),
202                Some(name),
203            ));
204        }
205    }
206}
207
208fn finding(
209    kind: FindingKind,
210    record_index: usize,
211    span: SourceSpan,
212    name: Option<&str>,
213) -> Finding {
214    Finding {
215        kind,
216        record_index,
217        span,
218        field_name: name.map(str::to_owned),
219    }
220}
221
222fn record_for_span(records: &[r_dcf_syntax::Record], span: SourceSpan) -> usize {
223    records
224        .iter()
225        .position(|record| {
226            let range = record.source_range();
227            span.start >= range.start && span.start <= range.end
228        })
229        .unwrap_or_else(|| records.len().saturating_sub(1))
230}
231
232pub(crate) fn valid_package_name(name: &str) -> bool {
233    let bytes = name.as_bytes();
234    bytes.len() >= 2
235        && bytes.first().is_some_and(u8::is_ascii_alphabetic)
236        && bytes.last().is_some_and(u8::is_ascii_alphanumeric)
237        && bytes
238            .iter()
239            .all(|byte| byte.is_ascii_alphanumeric() || *byte == b'.')
240}