rustxform-validate 0.1.1

Form validations and warnings for rustxform surveys.
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
//! Structural validations and non-fatal warnings over a parsed form.
//!
//! [`validate`] returns blocking [`ValidationError`]s (duplicate/empty names,
//! broken `${…}` references, unknown choice lists, malformed `range`
//! parameters and geo defaults). [`warnings`] returns non-fatal [`Warning`]s
//! (missing settings, unrecognized survey columns), which need the raw
//! workbook headers.

use std::collections::HashSet;

use rustxform_core::{Control, Kind, Node, Question, Survey};
use rustxform_expr::reference_names;
use rustxform_reader::Workbook;

/// A blocking validation problem.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ValidationError {
    /// A node name is used more than once.
    #[error("duplicate node name `{0}`")]
    DuplicateName(String),
    /// A node has an empty name.
    #[error("a `{0}` node has an empty name")]
    EmptyName(String),
    /// An expression references a name that is not a node in the form.
    #[error("`{owner}` references unknown name `{reference}`")]
    UnknownReference {
        /// Name of the question whose expression holds the reference.
        owner: String,
        /// The unresolved `${…}` name.
        reference: String,
    },
    /// A `select_*` question references a choice list that does not exist.
    #[error("`{question}` references unknown choice list `{list}`")]
    UnknownChoiceList {
        /// Name of the offending select question.
        question: String,
        /// The missing choice list name.
        list: String,
    },
    /// A `range` question has invalid `parameters`.
    #[error("`{question}` has invalid range parameters: {reason}")]
    InvalidRange {
        /// Name of the range question.
        question: String,
        /// Why the parameters are invalid.
        reason: String,
    },
    /// A geo question has a malformed `default` value.
    #[error("`{question}` has a malformed geo default `{value}`")]
    InvalidGeoDefault {
        /// Name of the geo question.
        question: String,
        /// The offending default value.
        value: String,
    },
}

/// A non-fatal warning.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum Warning {
    /// A recommended setting is absent (a default is used).
    #[error("the `{0}` setting is missing; a default is used")]
    MissingSetting(String),
    /// A survey column header is not recognized (possibly a typo).
    #[error("unrecognized survey column `{0}`")]
    UnknownColumn(String),
    /// A declared language has no recognized subtag code.
    #[error("language `{0}` has no recognized subtag code (e.g. `English (en)`)")]
    UnknownLanguageTag(String),
}

/// Validate a [`Survey`], returning all blocking problems (empty when valid).
#[must_use]
pub fn validate(survey: &Survey) -> Vec<ValidationError> {
    let mut errors = Vec::new();

    let mut names: HashSet<String> = HashSet::new();
    collect_names(&survey.children, &mut names, &mut errors);

    let lists: HashSet<&str> = survey.choices.iter().map(|c| c.name.as_str()).collect();
    check_nodes(&survey.children, &names, &lists, &mut errors);

    errors
}

/// Collect non-fatal warnings; needs the raw workbook for header checks.
#[must_use]
pub fn warnings(workbook: &Workbook, survey: &Survey) -> Vec<Warning> {
    let mut warnings = Vec::new();

    if survey.settings.title.is_none() {
        warnings.push(Warning::MissingSetting("form_title".to_owned()));
    }
    if survey.settings.form_id.is_none() {
        warnings.push(Warning::MissingSetting("form_id".to_owned()));
    }

    if let Some(header) = workbook.sheet("survey").and_then(|s| s.rows.first()) {
        for column in header {
            if !column.is_empty() && !is_known_survey_column(column) {
                warnings.push(Warning::UnknownColumn(column.clone()));
            }
        }
    }

    for language in &survey.languages {
        if !has_known_subtag(language) {
            warnings.push(Warning::UnknownLanguageTag(language.clone()));
        }
    }

    warnings
}

/// A language declares a recognized subtag as `Name (code)`: a 2-letter
/// ISO 639-1 code, or any 3-letter code (ISO 639-2/3, accepted by shape).
fn has_known_subtag(language: &str) -> bool {
    let Some(code) = language
        .rsplit_once('(')
        .and_then(|(_, rest)| rest.split_once(')'))
        .map(|(code, _)| code.trim().to_ascii_lowercase())
    else {
        return false;
    };
    match code.len() {
        2 => ISO_639_1.contains(&code.as_str()),
        3 => code.chars().all(|c| c.is_ascii_alphabetic()),
        _ => false,
    }
}

/// ISO 639-1 two-letter language codes.
#[rustfmt::skip]
const ISO_639_1: &[&str] = &[
    "aa","ab","ae","af","ak","am","an","ar","as","av","ay","az","ba","be","bg",
    "bh","bi","bm","bn","bo","br","bs","ca","ce","ch","co","cr","cs","cu","cv",
    "cy","da","de","dv","dz","ee","el","en","eo","es","et","eu","fa","ff","fi",
    "fj","fo","fr","fy","ga","gd","gl","gn","gu","gv","ha","he","hi","ho","hr",
    "ht","hu","hy","hz","ia","id","ie","ig","ii","ik","io","is","it","iu","ja",
    "jv","ka","kg","ki","kj","kk","kl","km","kn","ko","kr","ks","ku","kv","kw",
    "ky","la","lb","lg","li","ln","lo","lt","lu","lv","mg","mh","mi","mk","ml",
    "mn","mr","ms","mt","my","na","nb","nd","ne","ng","nl","nn","no","nr","nv",
    "ny","oc","oj","om","or","os","pa","pi","pl","ps","pt","qu","rm","rn","ro",
    "ru","rw","sa","sc","sd","se","sg","si","sk","sl","sm","sn","so","sq","sr",
    "ss","st","su","sv","sw","ta","te","tg","th","ti","tk","tl","tn","to","tr",
    "ts","tt","tw","ty","ug","uk","ur","uz","ve","vi","vo","wa","wo","xh","yi",
    "yo","za","zh","zu",
];

/// Gather node names, reporting empty and duplicate names as it goes.
fn collect_names(nodes: &[Node], names: &mut HashSet<String>, errors: &mut Vec<ValidationError>) {
    for node in nodes {
        let (name, kind, children) = match node {
            Node::Question(q) => (&q.name, "question", None),
            Node::Group(c) => (&c.name, "group", Some(&c.children)),
            Node::Repeat(c) => (&c.name, "repeat", Some(&c.children)),
        };

        if name.is_empty() {
            errors.push(ValidationError::EmptyName(kind.to_owned()));
        } else if !names.insert(name.clone()) {
            errors.push(ValidationError::DuplicateName(name.clone()));
        }

        if let Some(children) = children {
            collect_names(children, names, errors);
        }
    }
}

/// Check selects, references, ranges and geo defaults against known names.
fn check_nodes(
    nodes: &[Node],
    names: &HashSet<String>,
    lists: &HashSet<&str>,
    errors: &mut Vec<ValidationError>,
) {
    for node in nodes {
        match node {
            Node::Question(q) => check_question(q, names, lists, errors),
            Node::Group(c) | Node::Repeat(c) => check_nodes(&c.children, names, lists, errors),
        }
    }
}

fn check_question(
    q: &Question,
    names: &HashSet<String>,
    lists: &HashSet<&str>,
    errors: &mut Vec<ValidationError>,
) {
    match &q.kind {
        Kind::Select {
            list, file: None, ..
        } if !lists.contains(list.as_str()) => {
            errors.push(ValidationError::UnknownChoiceList {
                question: q.name.clone(),
                list: list.clone(),
            });
        }
        Kind::Builtin(b) if b.control == Some(Control::Range) => {
            if let Some(reason) = range_problem(q) {
                errors.push(ValidationError::InvalidRange {
                    question: q.name.clone(),
                    reason,
                });
            }
        }
        Kind::Builtin(b) if is_geo(b.bind_type) => {
            if let Some(value) = &q.default {
                if !is_valid_geo(value) {
                    errors.push(ValidationError::InvalidGeoDefault {
                        question: q.name.clone(),
                        value: value.clone(),
                    });
                }
            }
        }
        _ => {}
    }

    for expr in [
        &q.relevant,
        &q.constraint,
        &q.required,
        &q.readonly,
        &q.calculation,
        &q.choice_filter,
    ]
    .into_iter()
    .flatten()
    {
        for reference in reference_names(expr) {
            if !reference.contains('#') && !names.contains(&reference) {
                errors.push(ValidationError::UnknownReference {
                    owner: q.name.clone(),
                    reference,
                });
            }
        }
    }
}

/// Return a reason when a range question's parameters are invalid.
fn range_problem(q: &Question) -> Option<String> {
    let number = |key| q.parameter(key).and_then(|v| v.parse::<f64>().ok());
    let (start, end) = match (number("start"), number("end")) {
        // No bounds given: the defaults (1..10) are used.
        (None, None) if q.parameter("start").is_none() && q.parameter("end").is_none() => {
            return None;
        }
        (Some(start), Some(end)) => (start, end),
        _ => return Some("missing or non-numeric `start`/`end`".to_owned()),
    };
    if start >= end {
        return Some(format!("`start` ({start}) must be less than `end` ({end})"));
    }
    if let Some(step) = q.parameter("step") {
        match step.parse::<f64>() {
            Ok(step) if step > 0.0 => {}
            _ => return Some("`step` must be a positive number".to_owned()),
        }
    }
    None
}

/// Whether a bind type is one of the geo shapes.
fn is_geo(bind_type: &str) -> bool {
    matches!(bind_type, "geopoint" | "geotrace" | "geoshape")
}

/// A geo default is `;`-separated points, each `lat lon altitude accuracy`.
fn is_valid_geo(value: &str) -> bool {
    value
        .split(';')
        .filter(|p| !p.trim().is_empty())
        .all(|point| {
            let coords: Vec<&str> = point.split_whitespace().collect();
            coords.len() == 4 && coords.iter().all(|c| c.parse::<f64>().is_ok())
        })
}

/// Whether a survey column header (sans `::` qualifier) is recognized.
fn is_known_survey_column(column: &str) -> bool {
    let base = column.split("::").next().unwrap_or(column).trim();
    matches!(
        base,
        "type"
            | "name"
            | "label"
            | "hint"
            | "media"
            | "image"
            | "audio"
            | "video"
            | "appearance"
            | "relevant"
            | "constraint"
            | "constraint_message"
            | "required"
            | "required_message"
            | "read_only"
            | "readonly"
            | "calculation"
            | "parameters"
            | "default"
            | "choice_filter"
            | "repeat_count"
            | "trigger"
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use rustxform_parse::workbook_to_survey;
    use rustxform_reader::read_markdown;

    fn parse(md: &str) -> (Workbook, Survey) {
        let wb = read_markdown(md).unwrap();
        let survey = workbook_to_survey(&wb).unwrap();
        (wb, survey)
    }

    fn survey(md: &str) -> Survey {
        parse(md).1
    }

    #[test]
    fn valid_form_reports_nothing() {
        let md = "\
| survey |         |      |            |
|        | type    | name | label      |
|        | integer | age  | Age        |
|        | text    | who  | ${age} > 0 |
";
        assert!(validate(&survey(md)).is_empty());
    }

    #[test]
    fn flags_duplicate_names() {
        let md = "\
| survey |         |     |
|        | type    | name |
|        | text    | q    |
|        | integer | q    |
";
        assert!(validate(&survey(md)).contains(&ValidationError::DuplicateName("q".to_owned())));
    }

    #[test]
    fn flags_unknown_reference() {
        let md = "\
| survey |      |      |             |
|        | type | name | relevant    |
|        | text | q    | ${ghost} = 1 |
";
        assert!(
            validate(&survey(md)).contains(&ValidationError::UnknownReference {
                owner: "q".to_owned(),
                reference: "ghost".to_owned(),
            })
        );
    }

    #[test]
    fn flags_unknown_choice_list() {
        let md = "\
| survey |                  |      |
|        | type             | name |
|        | select_one missing | pick |
";
        assert!(
            validate(&survey(md)).contains(&ValidationError::UnknownChoiceList {
                question: "pick".to_owned(),
                list: "missing".to_owned(),
            })
        );
    }

    #[test]
    fn flags_invalid_range() {
        let md = "\
| survey |       |      |            |
|        | type  | name | parameters |
|        | range | r    | start=5 end=1 |
";
        let errors = validate(&survey(md));
        assert!(errors.iter().any(
            |e| matches!(e, ValidationError::InvalidRange { question, .. } if question == "r")
        ));
    }

    #[test]
    fn flags_malformed_geo_default() {
        let md = "\
| survey |          |      |         |
|        | type     | name | default |
|        | geopoint | loc  | 1 2     |
";
        assert!(
            validate(&survey(md)).contains(&ValidationError::InvalidGeoDefault {
                question: "loc".to_owned(),
                value: "1 2".to_owned(),
            })
        );
    }

    #[test]
    fn warns_on_missing_settings_and_unknown_columns() {
        let md = "\
| survey |      |      |          |
|        | type | name | relevnt  |
|        | text | q    |          |
";
        let (wb, survey) = parse(md);
        let warnings = warnings(&wb, &survey);
        assert!(warnings.contains(&Warning::UnknownColumn("relevnt".to_owned())));
        assert!(warnings.contains(&Warning::MissingSetting("form_id".to_owned())));
    }

    #[test]
    fn warns_on_language_without_known_subtag() {
        let md = "\
| survey |      |      |                |                     |
|        | type | name | label::English | label::French (fr)  |
|        | text | q    | Hi             | Salut               |
| settings |            |         |
|          | form_title | form_id |
|          | T          | t       |
";
        let (wb, survey) = parse(md);
        let warnings = warnings(&wb, &survey);
        assert!(warnings.contains(&Warning::UnknownLanguageTag("English".to_owned())));
        assert!(!warnings.contains(&Warning::UnknownLanguageTag("French (fr)".to_owned())));
    }
}