Skip to main content

rustxform_validate/
lib.rs

1//! Structural validations and non-fatal warnings over a parsed form.
2//!
3//! [`validate`] returns blocking [`ValidationError`]s (duplicate/empty names,
4//! broken `${…}` references, unknown choice lists, malformed `range`
5//! parameters and geo defaults). [`warnings`] returns non-fatal [`Warning`]s
6//! (missing settings, unrecognized survey columns), which need the raw
7//! workbook headers.
8
9use std::collections::HashSet;
10
11use rustxform_core::{Control, Kind, Node, Question, Survey};
12use rustxform_expr::reference_names;
13use rustxform_reader::Workbook;
14
15/// A blocking validation problem.
16#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
17pub enum ValidationError {
18    /// A node name is used more than once.
19    #[error("duplicate node name `{0}`")]
20    DuplicateName(String),
21    /// A node has an empty name.
22    #[error("a `{0}` node has an empty name")]
23    EmptyName(String),
24    /// An expression references a name that is not a node in the form.
25    #[error("`{owner}` references unknown name `{reference}`")]
26    UnknownReference {
27        /// Name of the question whose expression holds the reference.
28        owner: String,
29        /// The unresolved `${…}` name.
30        reference: String,
31    },
32    /// A `select_*` question references a choice list that does not exist.
33    #[error("`{question}` references unknown choice list `{list}`")]
34    UnknownChoiceList {
35        /// Name of the offending select question.
36        question: String,
37        /// The missing choice list name.
38        list: String,
39    },
40    /// A `range` question has invalid `parameters`.
41    #[error("`{question}` has invalid range parameters: {reason}")]
42    InvalidRange {
43        /// Name of the range question.
44        question: String,
45        /// Why the parameters are invalid.
46        reason: String,
47    },
48    /// A geo question has a malformed `default` value.
49    #[error("`{question}` has a malformed geo default `{value}`")]
50    InvalidGeoDefault {
51        /// Name of the geo question.
52        question: String,
53        /// The offending default value.
54        value: String,
55    },
56}
57
58/// A non-fatal warning.
59#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
60pub enum Warning {
61    /// A recommended setting is absent (a default is used).
62    #[error("the `{0}` setting is missing; a default is used")]
63    MissingSetting(String),
64    /// A survey column header is not recognized (possibly a typo).
65    #[error("unrecognized survey column `{0}`")]
66    UnknownColumn(String),
67    /// A declared language has no recognized subtag code.
68    #[error("language `{0}` has no recognized subtag code (e.g. `English (en)`)")]
69    UnknownLanguageTag(String),
70}
71
72/// Validate a [`Survey`], returning all blocking problems (empty when valid).
73#[must_use]
74pub fn validate(survey: &Survey) -> Vec<ValidationError> {
75    let mut errors = Vec::new();
76
77    let mut names: HashSet<String> = HashSet::new();
78    collect_names(&survey.children, &mut names, &mut errors);
79
80    let lists: HashSet<&str> = survey.choices.iter().map(|c| c.name.as_str()).collect();
81    check_nodes(&survey.children, &names, &lists, &mut errors);
82
83    errors
84}
85
86/// Collect non-fatal warnings; needs the raw workbook for header checks.
87#[must_use]
88pub fn warnings(workbook: &Workbook, survey: &Survey) -> Vec<Warning> {
89    let mut warnings = Vec::new();
90
91    if survey.settings.title.is_none() {
92        warnings.push(Warning::MissingSetting("form_title".to_owned()));
93    }
94    if survey.settings.form_id.is_none() {
95        warnings.push(Warning::MissingSetting("form_id".to_owned()));
96    }
97
98    if let Some(header) = workbook.sheet("survey").and_then(|s| s.rows.first()) {
99        for column in header {
100            if !column.is_empty() && !is_known_survey_column(column) {
101                warnings.push(Warning::UnknownColumn(column.clone()));
102            }
103        }
104    }
105
106    for language in &survey.languages {
107        if !has_known_subtag(language) {
108            warnings.push(Warning::UnknownLanguageTag(language.clone()));
109        }
110    }
111
112    warnings
113}
114
115/// A language declares a recognized subtag as `Name (code)`: a 2-letter
116/// ISO 639-1 code, or any 3-letter code (ISO 639-2/3, accepted by shape).
117fn has_known_subtag(language: &str) -> bool {
118    let Some(code) = language
119        .rsplit_once('(')
120        .and_then(|(_, rest)| rest.split_once(')'))
121        .map(|(code, _)| code.trim().to_ascii_lowercase())
122    else {
123        return false;
124    };
125    match code.len() {
126        2 => ISO_639_1.contains(&code.as_str()),
127        3 => code.chars().all(|c| c.is_ascii_alphabetic()),
128        _ => false,
129    }
130}
131
132/// ISO 639-1 two-letter language codes.
133#[rustfmt::skip]
134const ISO_639_1: &[&str] = &[
135    "aa","ab","ae","af","ak","am","an","ar","as","av","ay","az","ba","be","bg",
136    "bh","bi","bm","bn","bo","br","bs","ca","ce","ch","co","cr","cs","cu","cv",
137    "cy","da","de","dv","dz","ee","el","en","eo","es","et","eu","fa","ff","fi",
138    "fj","fo","fr","fy","ga","gd","gl","gn","gu","gv","ha","he","hi","ho","hr",
139    "ht","hu","hy","hz","ia","id","ie","ig","ii","ik","io","is","it","iu","ja",
140    "jv","ka","kg","ki","kj","kk","kl","km","kn","ko","kr","ks","ku","kv","kw",
141    "ky","la","lb","lg","li","ln","lo","lt","lu","lv","mg","mh","mi","mk","ml",
142    "mn","mr","ms","mt","my","na","nb","nd","ne","ng","nl","nn","no","nr","nv",
143    "ny","oc","oj","om","or","os","pa","pi","pl","ps","pt","qu","rm","rn","ro",
144    "ru","rw","sa","sc","sd","se","sg","si","sk","sl","sm","sn","so","sq","sr",
145    "ss","st","su","sv","sw","ta","te","tg","th","ti","tk","tl","tn","to","tr",
146    "ts","tt","tw","ty","ug","uk","ur","uz","ve","vi","vo","wa","wo","xh","yi",
147    "yo","za","zh","zu",
148];
149
150/// Gather node names, reporting empty and duplicate names as it goes.
151fn collect_names(nodes: &[Node], names: &mut HashSet<String>, errors: &mut Vec<ValidationError>) {
152    for node in nodes {
153        let (name, kind, children) = match node {
154            Node::Question(q) => (&q.name, "question", None),
155            Node::Group(c) => (&c.name, "group", Some(&c.children)),
156            Node::Repeat(c) => (&c.name, "repeat", Some(&c.children)),
157        };
158
159        if name.is_empty() {
160            errors.push(ValidationError::EmptyName(kind.to_owned()));
161        } else if !names.insert(name.clone()) {
162            errors.push(ValidationError::DuplicateName(name.clone()));
163        }
164
165        if let Some(children) = children {
166            collect_names(children, names, errors);
167        }
168    }
169}
170
171/// Check selects, references, ranges and geo defaults against known names.
172fn check_nodes(
173    nodes: &[Node],
174    names: &HashSet<String>,
175    lists: &HashSet<&str>,
176    errors: &mut Vec<ValidationError>,
177) {
178    for node in nodes {
179        match node {
180            Node::Question(q) => check_question(q, names, lists, errors),
181            Node::Group(c) | Node::Repeat(c) => check_nodes(&c.children, names, lists, errors),
182        }
183    }
184}
185
186fn check_question(
187    q: &Question,
188    names: &HashSet<String>,
189    lists: &HashSet<&str>,
190    errors: &mut Vec<ValidationError>,
191) {
192    match &q.kind {
193        Kind::Select {
194            list, file: None, ..
195        } if !lists.contains(list.as_str()) => {
196            errors.push(ValidationError::UnknownChoiceList {
197                question: q.name.clone(),
198                list: list.clone(),
199            });
200        }
201        Kind::Builtin(b) if b.control == Some(Control::Range) => {
202            if let Some(reason) = range_problem(q) {
203                errors.push(ValidationError::InvalidRange {
204                    question: q.name.clone(),
205                    reason,
206                });
207            }
208        }
209        Kind::Builtin(b) if is_geo(b.bind_type) => {
210            if let Some(value) = &q.default {
211                if !is_valid_geo(value) {
212                    errors.push(ValidationError::InvalidGeoDefault {
213                        question: q.name.clone(),
214                        value: value.clone(),
215                    });
216                }
217            }
218        }
219        _ => {}
220    }
221
222    for expr in [
223        &q.relevant,
224        &q.constraint,
225        &q.required,
226        &q.readonly,
227        &q.calculation,
228        &q.choice_filter,
229    ]
230    .into_iter()
231    .flatten()
232    {
233        for reference in reference_names(expr) {
234            if !reference.contains('#') && !names.contains(&reference) {
235                errors.push(ValidationError::UnknownReference {
236                    owner: q.name.clone(),
237                    reference,
238                });
239            }
240        }
241    }
242}
243
244/// Return a reason when a range question's parameters are invalid.
245fn range_problem(q: &Question) -> Option<String> {
246    let number = |key| q.parameter(key).and_then(|v| v.parse::<f64>().ok());
247    let (start, end) = match (number("start"), number("end")) {
248        // No bounds given: the defaults (1..10) are used.
249        (None, None) if q.parameter("start").is_none() && q.parameter("end").is_none() => {
250            return None;
251        }
252        (Some(start), Some(end)) => (start, end),
253        _ => return Some("missing or non-numeric `start`/`end`".to_owned()),
254    };
255    if start >= end {
256        return Some(format!("`start` ({start}) must be less than `end` ({end})"));
257    }
258    if let Some(step) = q.parameter("step") {
259        match step.parse::<f64>() {
260            Ok(step) if step > 0.0 => {}
261            _ => return Some("`step` must be a positive number".to_owned()),
262        }
263    }
264    None
265}
266
267/// Whether a bind type is one of the geo shapes.
268fn is_geo(bind_type: &str) -> bool {
269    matches!(bind_type, "geopoint" | "geotrace" | "geoshape")
270}
271
272/// A geo default is `;`-separated points, each `lat lon altitude accuracy`.
273fn is_valid_geo(value: &str) -> bool {
274    value
275        .split(';')
276        .filter(|p| !p.trim().is_empty())
277        .all(|point| {
278            let coords: Vec<&str> = point.split_whitespace().collect();
279            coords.len() == 4 && coords.iter().all(|c| c.parse::<f64>().is_ok())
280        })
281}
282
283/// Whether a survey column header (sans `::` qualifier) is recognized.
284fn is_known_survey_column(column: &str) -> bool {
285    let base = column.split("::").next().unwrap_or(column).trim();
286    matches!(
287        base,
288        "type"
289            | "name"
290            | "label"
291            | "hint"
292            | "media"
293            | "image"
294            | "audio"
295            | "video"
296            | "appearance"
297            | "relevant"
298            | "constraint"
299            | "constraint_message"
300            | "required"
301            | "required_message"
302            | "read_only"
303            | "readonly"
304            | "calculation"
305            | "parameters"
306            | "default"
307            | "choice_filter"
308            | "repeat_count"
309            | "trigger"
310    )
311}
312
313#[cfg(test)]
314mod tests {
315    use super::*;
316    use rustxform_parse::workbook_to_survey;
317    use rustxform_reader::read_markdown;
318
319    fn parse(md: &str) -> (Workbook, Survey) {
320        let wb = read_markdown(md).unwrap();
321        let survey = workbook_to_survey(&wb).unwrap();
322        (wb, survey)
323    }
324
325    fn survey(md: &str) -> Survey {
326        parse(md).1
327    }
328
329    #[test]
330    fn valid_form_reports_nothing() {
331        let md = "\
332| survey |         |      |            |
333|        | type    | name | label      |
334|        | integer | age  | Age        |
335|        | text    | who  | ${age} > 0 |
336";
337        assert!(validate(&survey(md)).is_empty());
338    }
339
340    #[test]
341    fn flags_duplicate_names() {
342        let md = "\
343| survey |         |     |
344|        | type    | name |
345|        | text    | q    |
346|        | integer | q    |
347";
348        assert!(validate(&survey(md)).contains(&ValidationError::DuplicateName("q".to_owned())));
349    }
350
351    #[test]
352    fn flags_unknown_reference() {
353        let md = "\
354| survey |      |      |             |
355|        | type | name | relevant    |
356|        | text | q    | ${ghost} = 1 |
357";
358        assert!(
359            validate(&survey(md)).contains(&ValidationError::UnknownReference {
360                owner: "q".to_owned(),
361                reference: "ghost".to_owned(),
362            })
363        );
364    }
365
366    #[test]
367    fn flags_unknown_choice_list() {
368        let md = "\
369| survey |                  |      |
370|        | type             | name |
371|        | select_one missing | pick |
372";
373        assert!(
374            validate(&survey(md)).contains(&ValidationError::UnknownChoiceList {
375                question: "pick".to_owned(),
376                list: "missing".to_owned(),
377            })
378        );
379    }
380
381    #[test]
382    fn flags_invalid_range() {
383        let md = "\
384| survey |       |      |            |
385|        | type  | name | parameters |
386|        | range | r    | start=5 end=1 |
387";
388        let errors = validate(&survey(md));
389        assert!(errors.iter().any(
390            |e| matches!(e, ValidationError::InvalidRange { question, .. } if question == "r")
391        ));
392    }
393
394    #[test]
395    fn flags_malformed_geo_default() {
396        let md = "\
397| survey |          |      |         |
398|        | type     | name | default |
399|        | geopoint | loc  | 1 2     |
400";
401        assert!(
402            validate(&survey(md)).contains(&ValidationError::InvalidGeoDefault {
403                question: "loc".to_owned(),
404                value: "1 2".to_owned(),
405            })
406        );
407    }
408
409    #[test]
410    fn warns_on_missing_settings_and_unknown_columns() {
411        let md = "\
412| survey |      |      |          |
413|        | type | name | relevnt  |
414|        | text | q    |          |
415";
416        let (wb, survey) = parse(md);
417        let warnings = warnings(&wb, &survey);
418        assert!(warnings.contains(&Warning::UnknownColumn("relevnt".to_owned())));
419        assert!(warnings.contains(&Warning::MissingSetting("form_id".to_owned())));
420    }
421
422    #[test]
423    fn warns_on_language_without_known_subtag() {
424        let md = "\
425| survey |      |      |                |                     |
426|        | type | name | label::English | label::French (fr)  |
427|        | text | q    | Hi             | Salut               |
428| settings |            |         |
429|          | form_title | form_id |
430|          | T          | t       |
431";
432        let (wb, survey) = parse(md);
433        let warnings = warnings(&wb, &survey);
434        assert!(warnings.contains(&Warning::UnknownLanguageTag("English".to_owned())));
435        assert!(!warnings.contains(&Warning::UnknownLanguageTag("French (fr)".to_owned())));
436    }
437}