Skip to main content

rustxform_xform2json/
lib.rs

1//! Parse an XForm back into the [`Survey`] model (the reverse direction).
2//!
3//! This is a near-complete inverse of the forward emitter. It recovers the form
4//! settings (title, id, version, style, instance_name), the full question tree
5//! (groups, repeats with `repeat_count`), bind logic (`relevant` / `constraint`
6//! / `required` / `read_only` / `calculate` and messages, as literal XPath),
7//! `appearance`, inline choice lists and `select_*_from_file`, top-level
8//! data-only nodes (`calculate`, metadata preloads, audit), entities, and
9//! `<itext>` — multilingual labels/hints/messages/choice labels plus label
10//! media and single-language guidance/media.
11//!
12//! Because the forward emitter only rewrites `${…}` tokens and passes other
13//! expressions through unchanged, these forms round-trip byte-identically:
14//! `emit(xform_to_survey(emit(survey))) == emit(survey)` (see the property test).
15//!
16//! Not recovered (uncommon): data-only nodes nested inside groups/repeats, and
17//! `pulldata()` CSV instances. Use it to import or inspect an XForm.
18
19use std::collections::HashMap;
20
21use quick_xml::events::Event;
22use quick_xml::reader::Reader;
23use rustxform_core::{
24    Choice, ChoiceList, Container, Entity, Kind, Localized, Media, Node, Question, SelectType,
25    Survey, resolve_builtin,
26};
27
28/// An error produced while parsing an XForm.
29#[derive(Debug, thiserror::Error)]
30pub enum Xform2JsonError {
31    /// The XML could not be parsed.
32    #[error("xml parse error: {0}")]
33    Xml(String),
34}
35
36/// Body control element names handled by the reverse parser.
37const CONTROLS: &[&str] = &[
38    "input", "select1", "select", "rank", "trigger", "upload", "range",
39];
40
41/// Parse an XForm document into a [`Survey`].
42///
43/// # Errors
44///
45/// Returns [`Xform2JsonError::Xml`] if the document is not well-formed.
46pub fn xform_to_survey(xml: &str) -> Result<Survey, Xform2JsonError> {
47    let binds = collect_binds(xml)?;
48    let meta = collect_metadata(xml)?;
49    let extern_files = collect_external_files(xml)?;
50    let body = collect_body_nodes(xml, &binds, &extern_files)?;
51    let order = collect_instance_order(xml)?;
52    let choices = collect_choices(xml)?;
53    let itext = collect_itext(xml)?;
54
55    let mut survey = Survey::default();
56    survey.settings.title = meta.title;
57    survey.settings.form_id = meta.form_id;
58    survey.settings.version = meta.version;
59    survey.settings.style = meta.style;
60    survey.settings.instance_name = binds
61        .get(&format!("/{ROOT}/meta/instanceName"))
62        .and_then(|b| b.calculate.clone());
63    survey.children = merge_top_level(order, body, &binds);
64    survey.choices = choices;
65    survey.audit = binds.contains_key(&format!("/{ROOT}/meta/audit"));
66    survey.entity = collect_entity(xml, &binds)?;
67    apply_itext(&mut survey, &itext);
68    Ok(survey)
69}
70
71/// Reconstruct the [`Entity`] declaration from the `<meta><entity>` element
72/// (for the dataset) and its calculate binds. The `@id` bind carries a
73/// calculate in update mode but not in create mode, which distinguishes them.
74fn collect_entity(
75    xml: &str,
76    binds: &HashMap<String, Bind>,
77) -> Result<Option<Entity>, Xform2JsonError> {
78    let mut reader = Reader::from_str(xml);
79    reader.config_mut().trim_text(true);
80    let mut dataset = None;
81    loop {
82        match read(&mut reader)? {
83            Event::Eof => break,
84            Event::Start(e) | Event::Empty(e) if local_name(e.name().as_ref()) == "entity" => {
85                if let Some(value) = attr(&e, "dataset") {
86                    dataset = Some(value);
87                    break;
88                }
89            }
90            _ => {}
91        }
92    }
93    let Some(dataset) = dataset else {
94        return Ok(None);
95    };
96    let base = format!("/{ROOT}/meta/entity");
97    let calc = |suffix: &str| {
98        binds
99            .get(&format!("{base}/{suffix}"))
100            .and_then(|b| b.calculate.clone())
101    };
102    Ok(Some(Entity {
103        dataset,
104        label: calc("label"),
105        entity_id: calc("@id"),
106        create_if: calc("@create"),
107        update_if: calc("@update"),
108    }))
109}
110
111/// Decoded `<itext>` translations: languages in order, the default one, and per
112/// text id the plain values, the media (`form=image|audio|video`) and the
113/// guidance (`form=guidance`) values — each as `(lang, …)` lists.
114#[derive(Default)]
115struct Itext {
116    languages: Vec<String>,
117    default_language: Option<String>,
118    values: HashMap<String, Vec<(String, String)>>,
119    media: HashMap<String, Vec<(String, String, String)>>,
120    guidance: HashMap<String, Vec<(String, String)>>,
121}
122
123/// Parse the `<itext>` block. A lone `default` pseudo-language (single-language
124/// forms needing itext for guidance/media) is kept; [`apply_itext`] treats it as
125/// non-multilingual and does not set `survey.languages`.
126fn collect_itext(xml: &str) -> Result<Itext, Xform2JsonError> {
127    let mut reader = Reader::from_str(xml);
128    reader.config_mut().trim_text(true);
129
130    let mut itext = Itext::default();
131    let mut in_itext = false;
132    let mut lang: Option<String> = None;
133    let mut text_id: Option<String> = None;
134    let mut in_value = false;
135    let mut form: Option<String> = None;
136    let mut buffer = String::new();
137
138    loop {
139        match read(&mut reader)? {
140            Event::Eof => break,
141            Event::Start(e) => match local_name(e.name().as_ref()).as_str() {
142                "itext" => in_itext = true,
143                "translation" if in_itext => {
144                    let value = attr(&e, "lang").unwrap_or_default();
145                    if attr(&e, "default").is_some() {
146                        itext.default_language = Some(value.clone());
147                    }
148                    if !itext.languages.contains(&value) {
149                        itext.languages.push(value.clone());
150                    }
151                    lang = Some(value);
152                }
153                "text" if in_itext => text_id = attr(&e, "id"),
154                "value" if in_itext => {
155                    form = attr(&e, "form");
156                    in_value = true;
157                    buffer.clear();
158                }
159                _ => {}
160            },
161            Event::Empty(e)
162                if in_itext
163                    && local_name(e.name().as_ref()) == "value"
164                    && attr(&e, "form").is_none() =>
165            {
166                record_itext(&mut itext, &text_id, &lang, None, String::new());
167            }
168            Event::Text(t) if in_value => buffer.push_str(&t.unescape().map_err(xml_err)?),
169            Event::End(e) => match local_name(e.name().as_ref()).as_str() {
170                "itext" => in_itext = false,
171                "value" if in_value => {
172                    record_itext(
173                        &mut itext,
174                        &text_id,
175                        &lang,
176                        form.take(),
177                        std::mem::take(&mut buffer),
178                    );
179                    in_value = false;
180                }
181                "text" => text_id = None,
182                "translation" => lang = None,
183                _ => {}
184            },
185            _ => {}
186        }
187    }
188    Ok(itext)
189}
190
191/// Record a `<value>` for the current text id: a plain value, a `guidance`
192/// value, or a media value (whose `jr://dir/file` is reduced to `file`).
193fn record_itext(
194    itext: &mut Itext,
195    id: &Option<String>,
196    lang: &Option<String>,
197    form: Option<String>,
198    value: String,
199) {
200    let (Some(id), Some(lang)) = (id, lang) else {
201        return;
202    };
203    match form.as_deref() {
204        None => itext
205            .values
206            .entry(id.clone())
207            .or_default()
208            .push((lang.clone(), value)),
209        Some("guidance") => itext
210            .guidance
211            .entry(id.clone())
212            .or_default()
213            .push((lang.clone(), value)),
214        Some(media_form) => {
215            let file = value.rsplit('/').next().unwrap_or(&value).to_owned();
216            itext.media.entry(id.clone()).or_default().push((
217                lang.clone(),
218                media_form.to_owned(),
219                file,
220            ));
221        }
222    }
223}
224
225/// Apply decoded translations. A real multilingual form sets `survey.languages`
226/// and fills per-language labels/hints/messages/choices; a single-language form
227/// with itext only recovers its media and guidance from the `default` entries.
228fn apply_itext(survey: &mut Survey, itext: &Itext) {
229    if itext.languages.is_empty() {
230        return;
231    }
232    let ml = itext.languages != ["default"];
233    if ml {
234        survey.languages = itext.languages.clone();
235        survey.settings.default_language = itext.default_language.clone();
236    }
237    apply_itext_nodes(&mut survey.children, &format!("/{ROOT}"), itext, ml);
238    if ml {
239        for list in &mut survey.choices {
240            for (i, item) in list.items.iter_mut().enumerate() {
241                if let Some(values) = itext.values.get(&format!("{}-{}", list.name, i)) {
242                    item.label = localized_pick(values, &itext.languages, true);
243                }
244            }
245        }
246    }
247}
248
249fn apply_itext_nodes(nodes: &mut [Node], parent: &str, itext: &Itext, ml: bool) {
250    let langs = &itext.languages;
251    for node in nodes {
252        match node {
253            Node::Question(q) => {
254                let path = format!("{parent}/{}", q.name);
255                if let Some(v) = itext.values.get(&format!("{path}:label")) {
256                    q.label = localized_pick(v, langs, ml);
257                }
258                if let Some(m) = itext.media.get(&format!("{path}:label")) {
259                    q.media = build_media(m, ml);
260                }
261                if let Some(v) = itext.values.get(&format!("{path}:hint")) {
262                    q.hint = localized_pick(v, langs, ml);
263                }
264                if let Some(g) = itext.guidance.get(&format!("{path}:hint")) {
265                    q.guidance_hint = localized_pick(g, langs, ml);
266                }
267                if ml {
268                    if let Some(v) = itext.values.get(&format!("{path}:jr:constraintMsg")) {
269                        q.constraint_message = localized_pick(v, langs, true);
270                    }
271                    if let Some(v) = itext.values.get(&format!("{path}:jr:requiredMsg")) {
272                        q.required_message = localized_pick(v, langs, true);
273                    }
274                }
275            }
276            Node::Group(c) | Node::Repeat(c) => {
277                apply_itext_nodes(&mut c.children, &format!("{parent}/{}", c.name), itext, ml);
278            }
279        }
280    }
281}
282
283/// Build a [`Localized`] from `(lang, value)` pairs: per-language when `ml`,
284/// else the single `default` value.
285fn localized_pick(values: &[(String, String)], languages: &[String], ml: bool) -> Localized {
286    if ml {
287        let langs = languages
288            .iter()
289            .filter_map(|lang| {
290                values
291                    .iter()
292                    .find(|(vlang, _)| vlang == lang)
293                    .map(|(_, value)| (lang.clone(), value.clone()))
294            })
295            .collect();
296        Localized {
297            default: None,
298            langs,
299        }
300    } else {
301        Localized {
302            default: values
303                .iter()
304                .find(|(lang, _)| lang == "default")
305                .map(|(_, value)| value.clone()),
306            langs: Vec::new(),
307        }
308    }
309}
310
311/// Rebuild label [`Media`] from `(lang, form, file)` entries, grouped by form in
312/// first-seen order.
313fn build_media(entries: &[(String, String, String)], ml: bool) -> Vec<Media> {
314    let mut media: Vec<Media> = Vec::new();
315    for (lang, form, file) in entries {
316        let idx = media
317            .iter()
318            .position(|m| &m.form == form)
319            .unwrap_or_else(|| {
320                media.push(Media {
321                    form: form.clone(),
322                    files: Localized::default(),
323                });
324                media.len() - 1
325            });
326        if ml {
327            media[idx].files.langs.push((lang.clone(), file.clone()));
328        } else {
329            media[idx].files.default = Some(file.clone());
330        }
331    }
332    media
333}
334
335/// Primary-instance root element name.
336const ROOT: &str = "data";
337
338/// Merge the body-control tree with the primary-instance order, inserting
339/// top-level data-only nodes (`calculate`, metadata preloads) that carry no
340/// body control, at their correct positions. Nested data-only nodes are not
341/// yet recovered.
342fn merge_top_level(
343    order: Vec<String>,
344    body: Vec<Node>,
345    binds: &HashMap<String, Bind>,
346) -> Vec<Node> {
347    let mut result = Vec::with_capacity(order.len());
348    let mut body = body.into_iter().peekable();
349    for name in order {
350        if body.peek().is_some_and(|n| node_name(n) == name.as_str()) {
351            result.push(body.next().expect("peeked"));
352        } else if let Some(bind) = binds.get(&format!("/{ROOT}/{name}")) {
353            result.push(Node::Question(data_only_question(name, bind)));
354        }
355    }
356    result.extend(body);
357    result
358}
359
360/// A node's own name.
361fn node_name(node: &Node) -> &str {
362    match node {
363        Node::Question(q) => &q.name,
364        Node::Group(c) | Node::Repeat(c) => &c.name,
365    }
366}
367
368/// Build a data-only [`Question`] (no body control) from its bind: a metadata
369/// preload, or a `calculate`.
370fn data_only_question(name: String, bind: &Bind) -> Question {
371    let token = match (bind.preload.as_deref(), bind.preload_params.as_deref()) {
372        (Some(preload), Some(params)) => preload_token(preload, params),
373        _ if bind.calculate.is_some() => "calculate",
374        _ => "text",
375    };
376    let kind =
377        resolve_builtin(token).map_or_else(|| Kind::Unknown(token.to_owned()), Kind::Builtin);
378    Question {
379        kind,
380        name,
381        label: Localized::default(),
382        hint: Localized::default(),
383        guidance_hint: Localized::default(),
384        appearance: None,
385        calculation: bind.calculate.clone(),
386        relevant: bind.relevant.clone(),
387        constraint: bind.constraint.clone(),
388        required: bind.required.clone(),
389        readonly: bind.readonly.clone(),
390        constraint_message: Localized::default(),
391        required_message: Localized::default(),
392        parameters: Vec::new(),
393        media: Vec::new(),
394        default: None,
395        choice_filter: None,
396        save_to: bind.save_to.clone(),
397        trigger: None,
398    }
399}
400
401/// Reverse the `jr:preload` / `jr:preloadParams` pair to its XLSForm type token.
402fn preload_token(preload: &str, params: &str) -> &'static str {
403    match (preload, params) {
404        ("timestamp", "start") => "start",
405        ("timestamp", "end") => "end",
406        ("date", "today") => "today",
407        ("property", "deviceid") => "deviceid",
408        ("property", "username") => "username",
409        ("property", "phonenumber") => "phonenumber",
410        ("property", "email") => "email",
411        ("property", "simserial") => "simserial",
412        ("property", "subscriberid") => "subscriberid",
413        _ => "calculate",
414    }
415}
416
417/// Collect the primary instance's top-level child element names in order,
418/// skipping `meta`, synthetic `…_count` nodes, and the duplicate repeat
419/// instance (keeping the `jr:template` occurrence only).
420fn collect_instance_order(xml: &str) -> Result<Vec<String>, Xform2JsonError> {
421    let mut reader = Reader::from_str(xml);
422    reader.config_mut().trim_text(true);
423
424    let mut names = Vec::new();
425    let mut in_primary = false;
426    let mut depth = 0i32;
427    let mut skip_next: Option<String> = None;
428
429    loop {
430        match read(&mut reader)? {
431            Event::Eof => break,
432            Event::Start(e) => {
433                let name = local_name(e.name().as_ref());
434                if !in_primary {
435                    if name == "instance" && attr(&e, "id").is_none() && attr(&e, "src").is_none() {
436                        in_primary = true;
437                        depth = 0;
438                    }
439                    continue;
440                }
441                if depth == 1 {
442                    let is_template = attr(&e, "template").is_some();
443                    record_top_level(&name, is_template, &mut names, &mut skip_next);
444                }
445                depth += 1;
446            }
447            Event::Empty(e) if in_primary && depth == 1 => {
448                let name = local_name(e.name().as_ref());
449                record_top_level(&name, false, &mut names, &mut skip_next);
450            }
451            Event::End(e) if in_primary => {
452                if local_name(e.name().as_ref()) == "instance" {
453                    in_primary = false;
454                } else {
455                    depth -= 1;
456                }
457            }
458            _ => {}
459        }
460    }
461    Ok(names)
462}
463
464/// Record a top-level instance node name, honoring the skip rules.
465fn record_top_level(
466    name: &str,
467    is_template: bool,
468    names: &mut Vec<String>,
469    skip_next: &mut Option<String>,
470) {
471    if name == "meta" || name.ends_with("_count") {
472        return;
473    }
474    if skip_next.as_deref() == Some(name) {
475        *skip_next = None; // the live twin of a repeat template
476        return;
477    }
478    names.push(name.to_owned());
479    if is_template {
480        *skip_next = Some(name.to_owned());
481    }
482}
483
484/// Reconstruct inline choice lists from secondary instances of the form
485/// `<instance id="L"><root><item><name>…</name><label>…</label>…</item>…`.
486///
487/// Instances with a `src` (external files, `pulldata`, last-saved) and the
488/// primary instance (which has no `id`) are skipped.
489fn collect_choices(xml: &str) -> Result<Vec<ChoiceList>, Xform2JsonError> {
490    let mut reader = Reader::from_str(xml);
491    reader.config_mut().trim_text(true);
492
493    let mut lists: Vec<ChoiceList> = Vec::new();
494    let mut list: Option<ChoiceList> = None;
495    let mut item: Option<Choice> = None;
496    let mut field: Option<String> = None;
497    let mut buffer = String::new();
498
499    loop {
500        match read(&mut reader)? {
501            Event::Eof => break,
502            Event::Start(e) | Event::Empty(e) => {
503                let name = local_name(e.name().as_ref());
504                if name == "instance" {
505                    if let (Some(id), None) = (attr(&e, "id"), attr(&e, "src")) {
506                        list = Some(ChoiceList {
507                            name: id,
508                            items: Vec::new(),
509                        });
510                    }
511                } else if list.is_some() {
512                    match name.as_str() {
513                        "root" => {}
514                        "item" => {
515                            item = Some(Choice {
516                                name: String::new(),
517                                label: Localized::default(),
518                                extra: Vec::new(),
519                            });
520                        }
521                        _ if item.is_some() => {
522                            field = Some(name);
523                            buffer.clear();
524                        }
525                        _ => {}
526                    }
527                }
528            }
529            Event::Text(t) if field.is_some() => {
530                buffer.push_str(&t.unescape().map_err(xml_err)?);
531            }
532            Event::End(e) => {
533                let name = local_name(e.name().as_ref());
534                if list.is_none() {
535                    continue;
536                }
537                if Some(name.as_str()) == field.as_deref() {
538                    if let Some(choice) = item.as_mut() {
539                        let value = std::mem::take(&mut buffer);
540                        match name.as_str() {
541                            "name" => choice.name = value,
542                            "label" => choice.label.default = Some(value),
543                            // Multilingual items reference their label via itext.
544                            "itextId" => {}
545                            other => choice.extra.push((other.to_owned(), value)),
546                        }
547                    }
548                    field = None;
549                } else if name == "item" {
550                    if let (Some(choice), Some(choice_list)) = (item.take(), list.as_mut()) {
551                        choice_list.items.push(choice);
552                    }
553                } else if name == "instance" {
554                    if let Some(choice_list) = list.take() {
555                        lists.push(choice_list);
556                    }
557                }
558            }
559            _ => {}
560        }
561    }
562    Ok(lists)
563}
564
565/// A `<bind>`'s recovered attributes, keyed by nodeset in [`collect_binds`].
566#[derive(Default, Clone)]
567struct Bind {
568    ty: Option<String>,
569    relevant: Option<String>,
570    constraint: Option<String>,
571    required: Option<String>,
572    readonly: Option<String>,
573    calculate: Option<String>,
574    constraint_msg: Option<String>,
575    required_msg: Option<String>,
576    preload: Option<String>,
577    preload_params: Option<String>,
578    save_to: Option<String>,
579}
580
581/// `nodeset` → its [`Bind`], from the model binds.
582fn collect_binds(xml: &str) -> Result<HashMap<String, Bind>, Xform2JsonError> {
583    let mut reader = Reader::from_str(xml);
584    reader.config_mut().trim_text(true);
585    let mut binds = HashMap::new();
586    loop {
587        match read(&mut reader)? {
588            Event::Eof => break,
589            Event::Start(e) | Event::Empty(e) if local_name(e.name().as_ref()) == "bind" => {
590                if let Some(nodeset) = attr(&e, "nodeset") {
591                    binds.insert(
592                        nodeset,
593                        Bind {
594                            ty: attr(&e, "type"),
595                            relevant: attr(&e, "relevant"),
596                            constraint: attr(&e, "constraint"),
597                            required: attr(&e, "required"),
598                            readonly: attr(&e, "readonly"),
599                            calculate: attr(&e, "calculate"),
600                            constraint_msg: attr(&e, "constraintMsg"),
601                            required_msg: attr(&e, "requiredMsg"),
602                            preload: attr(&e, "preload"),
603                            preload_params: attr(&e, "preloadParams"),
604                            save_to: attr(&e, "saveto"),
605                        },
606                    );
607                }
608            }
609            _ => {}
610        }
611    }
612    Ok(binds)
613}
614
615/// Form-level metadata recovered from outside the binds/body.
616#[derive(Default)]
617struct Meta {
618    title: Option<String>,
619    form_id: Option<String>,
620    version: Option<String>,
621    style: Option<String>,
622}
623
624/// Recover the `title` (`<h:title>`), the `form_id` and `version` (the primary
625/// instance root's `id`/`version`), and the `style` (the body `class`).
626fn collect_metadata(xml: &str) -> Result<Meta, Xform2JsonError> {
627    let mut reader = Reader::from_str(xml);
628    reader.config_mut().trim_text(true);
629    let mut meta = Meta::default();
630    let mut in_title = false;
631    let mut expect_root = false;
632    loop {
633        match read(&mut reader)? {
634            Event::Eof => break,
635            Event::Start(e) | Event::Empty(e) => match local_name(e.name().as_ref()).as_str() {
636                "title" => in_title = true,
637                "body" => meta.style = attr(&e, "class"),
638                "instance" if attr(&e, "id").is_none() && meta.form_id.is_none() => {
639                    expect_root = true;
640                }
641                _ if expect_root => {
642                    meta.form_id = attr(&e, "id");
643                    meta.version = attr(&e, "version");
644                    expect_root = false;
645                }
646                _ => {}
647            },
648            Event::Text(t) if in_title => {
649                meta.title = Some(t.unescape().map_err(xml_err)?.into_owned());
650            }
651            Event::End(e) if local_name(e.name().as_ref()) == "title" => in_title = false,
652            _ => {}
653        }
654    }
655    Ok(meta)
656}
657
658/// Map each external instance id to its file name, from
659/// `<instance id="L" src="jr://file[-csv]/NAME"/>`. These back
660/// `select_*_from_file` questions.
661fn collect_external_files(xml: &str) -> Result<HashMap<String, String>, Xform2JsonError> {
662    let mut reader = Reader::from_str(xml);
663    reader.config_mut().trim_text(true);
664    let mut files = HashMap::new();
665    loop {
666        match read(&mut reader)? {
667            Event::Eof => break,
668            Event::Start(e) | Event::Empty(e) if local_name(e.name().as_ref()) == "instance" => {
669                if let (Some(id), Some(src)) = (attr(&e, "id"), attr(&e, "src")) {
670                    if src.starts_with("jr://file/") || src.starts_with("jr://file-csv/") {
671                        if let Some(file) = src.rsplit('/').next() {
672                            files.insert(id, file.to_owned());
673                        }
674                    }
675                }
676            }
677            _ => {}
678        }
679    }
680    Ok(files)
681}
682
683/// A body control being assembled.
684struct Partial {
685    tag: String,
686    reference: String,
687    mediatype: Option<String>,
688    appearance: Option<String>,
689    list: Option<String>,
690    label: Option<String>,
691    hint: Option<String>,
692}
693
694/// A group/repeat being assembled on the parse stack.
695struct Frame {
696    name: String,
697    label: Option<String>,
698    appearance: Option<String>,
699    is_repeat: bool,
700    count: Option<String>,
701    children: Vec<Node>,
702}
703
704/// Walk the body into a node tree, reconstructing groups and repeats.
705///
706/// The forward emitter wraps a repeat in a `<group>` holding a `<repeat>`, so a
707/// group whose body contains a `<repeat>` becomes a [`Node::Repeat`].
708fn collect_body_nodes(
709    xml: &str,
710    binds: &HashMap<String, Bind>,
711    extern_files: &HashMap<String, String>,
712) -> Result<Vec<Node>, Xform2JsonError> {
713    let mut reader = Reader::from_str(xml);
714    reader.config_mut().trim_text(true);
715
716    let mut root: Vec<Node> = Vec::new();
717    let mut stack: Vec<Frame> = Vec::new();
718    let mut current: Option<Partial> = None;
719    let mut in_label = false;
720    let mut in_group_label = false;
721    let mut in_hint = false;
722    let mut in_itemset = false;
723    let mut in_body = false;
724
725    loop {
726        match read(&mut reader)? {
727            Event::Eof => break,
728            Event::Start(e) | Event::Empty(e) => {
729                let name = local_name(e.name().as_ref());
730                if name == "body" {
731                    in_body = true;
732                } else if !in_body {
733                    continue;
734                } else if CONTROLS.contains(&name.as_str()) {
735                    current = Some(Partial {
736                        tag: name,
737                        reference: attr(&e, "ref").unwrap_or_default(),
738                        mediatype: attr(&e, "mediatype"),
739                        appearance: attr(&e, "appearance"),
740                        list: None,
741                        label: None,
742                        hint: None,
743                    });
744                } else if name == "group" {
745                    stack.push(Frame {
746                        name: last_segment(attr(&e, "ref").as_deref().unwrap_or_default()),
747                        label: None,
748                        appearance: attr(&e, "appearance"),
749                        is_repeat: false,
750                        count: None,
751                        children: Vec::new(),
752                    });
753                } else if name == "repeat" {
754                    if let Some(top) = stack.last_mut() {
755                        top.is_repeat = true;
756                        if attr(&e, "count").is_some() {
757                            let nodeset = attr(&e, "nodeset").unwrap_or_default();
758                            top.count = binds
759                                .get(&format!("{nodeset}_count"))
760                                .and_then(|b| b.calculate.clone());
761                        }
762                    }
763                } else if name == "itemset" {
764                    in_itemset = true;
765                    if let Some(p) = current.as_mut() {
766                        p.list = attr(&e, "nodeset").and_then(|n| instance_id(&n));
767                    }
768                } else if name == "label" && attr(&e, "ref").is_none() {
769                    // An itext `<label ref="jr:itext(…)"/>` carries no inline
770                    // text; the value is recovered from <itext> instead.
771                    if current.is_some() && !in_itemset {
772                        in_label = true;
773                    } else if current.is_none() && !stack.is_empty() {
774                        in_group_label = true;
775                    }
776                } else if name == "hint" && current.is_some() && attr(&e, "ref").is_none() {
777                    in_hint = true;
778                }
779            }
780            Event::Text(t) if in_label => {
781                if let Some(p) = current.as_mut() {
782                    p.label = Some(t.unescape().map_err(xml_err)?.into_owned());
783                }
784            }
785            Event::Text(t) if in_group_label => {
786                if let Some(frame) = stack.last_mut() {
787                    frame.label = Some(t.unescape().map_err(xml_err)?.into_owned());
788                }
789            }
790            Event::Text(t) if in_hint => {
791                if let Some(p) = current.as_mut() {
792                    p.hint = Some(t.unescape().map_err(xml_err)?.into_owned());
793                }
794            }
795            Event::End(e) => match local_name(e.name().as_ref()).as_str() {
796                "label" if in_group_label => in_group_label = false,
797                "label" => in_label = false,
798                "hint" => in_hint = false,
799                "itemset" => in_itemset = false,
800                "repeat" => {}
801                "group" => {
802                    if let Some(frame) = stack.pop() {
803                        let is_repeat = frame.is_repeat;
804                        let container = Container {
805                            name: frame.name,
806                            label: frame.label,
807                            appearance: frame.appearance,
808                            count: frame.count,
809                            children: frame.children,
810                        };
811                        let node = if is_repeat {
812                            Node::Repeat(container)
813                        } else {
814                            Node::Group(container)
815                        };
816                        push_node(node, &mut stack, &mut root);
817                    }
818                }
819                name if CONTROLS.contains(&name) => {
820                    if let Some(p) = current.take() {
821                        let question = to_question(p, binds, extern_files);
822                        push_node(Node::Question(question), &mut stack, &mut root);
823                    }
824                }
825                _ => {}
826            },
827            _ => {}
828        }
829    }
830    Ok(root)
831}
832
833/// Append a finished node to the innermost open frame, or to the root.
834fn push_node(node: Node, stack: &mut [Frame], root: &mut Vec<Node>) {
835    match stack.last_mut() {
836        Some(frame) => frame.children.push(node),
837        None => root.push(node),
838    }
839}
840
841/// The last `/`-separated segment of a nodeset (`/data/g/x` → `x`).
842fn last_segment(reference: &str) -> String {
843    reference.rsplit('/').next().unwrap_or("").to_owned()
844}
845
846/// Build a [`Question`] from an assembled control and the binds.
847fn to_question(
848    p: Partial,
849    binds: &HashMap<String, Bind>,
850    extern_files: &HashMap<String, String>,
851) -> Question {
852    let name = p.reference.rsplit('/').next().unwrap_or("").to_owned();
853    let bind = binds.get(&p.reference).cloned().unwrap_or_default();
854    let bind_type = bind.ty.as_deref().unwrap_or("string");
855    // A select whose list has an external instance is a `select_*_from_file`.
856    let file = p.list.as_ref().and_then(|l| extern_files.get(l).cloned());
857    let kind = match infer_kind(&p.tag, bind_type, p.list, p.mediatype.as_deref()) {
858        Kind::Select { select, list, .. } => Kind::Select { select, list, file },
859        other => other,
860    };
861
862    Question {
863        kind,
864        name,
865        label: single_lang(p.label),
866        hint: single_lang(p.hint),
867        guidance_hint: Localized::default(),
868        appearance: p.appearance,
869        calculation: bind.calculate,
870        relevant: bind.relevant,
871        constraint: bind.constraint,
872        required: bind.required,
873        readonly: bind.readonly,
874        constraint_message: single_lang(bind.constraint_msg),
875        required_message: single_lang(bind.required_msg),
876        parameters: Vec::new(),
877        media: Vec::new(),
878        default: None,
879        choice_filter: None,
880        save_to: bind.save_to,
881        trigger: None,
882    }
883}
884
885/// Wrap an optional single-language string into a [`Localized`].
886fn single_lang(text: Option<String>) -> Localized {
887    Localized {
888        default: text,
889        langs: Vec::new(),
890    }
891}
892
893/// Infer a [`Kind`] from a control tag, bind type and (for selects) list.
894fn infer_kind(tag: &str, bind_type: &str, list: Option<String>, mediatype: Option<&str>) -> Kind {
895    let select = match tag {
896        "select1" => Some(SelectType::One),
897        "select" => Some(SelectType::Multiple),
898        "rank" => Some(SelectType::Rank),
899        _ => None,
900    };
901    match select {
902        Some(select) => Kind::Select {
903            select,
904            list: list.unwrap_or_default(),
905            file: None,
906        },
907        None => {
908            let token = builtin_token(tag, bind_type, mediatype);
909            resolve_builtin(&token).map_or(Kind::Unknown(token.clone()), Kind::Builtin)
910        }
911    }
912}
913
914/// Recover the XLSForm type token for a non-select control.
915fn builtin_token(tag: &str, bind_type: &str, mediatype: Option<&str>) -> String {
916    match tag {
917        "trigger" => "acknowledge",
918        "range" => "range",
919        "upload" => match mediatype {
920            Some("audio/*") => "audio",
921            Some("video/*") => "video",
922            _ => "image",
923        },
924        _ => match bind_type {
925            "int" => "integer",
926            "decimal" => "decimal",
927            "date" => "date",
928            "time" => "time",
929            "dateTime" => "dateTime",
930            "geopoint" => "geopoint",
931            "geotrace" => "geotrace",
932            "geoshape" => "geoshape",
933            "barcode" => "barcode",
934            _ => "text",
935        },
936    }
937    .to_owned()
938}
939
940/// Extract `cities` from `instance('cities')/root/item[...]`.
941fn instance_id(nodeset: &str) -> Option<String> {
942    let start = nodeset.find("instance('")? + "instance('".len();
943    let end = nodeset[start..].find('\'')? + start;
944    Some(nodeset[start..end].to_owned())
945}
946
947/// The local part of a possibly-prefixed XML name (`h:title` → `title`).
948fn local_name(raw: &[u8]) -> String {
949    let name = String::from_utf8_lossy(raw);
950    name.rsplit(':').next().unwrap_or(&name).to_owned()
951}
952
953/// Read one event, mapping XML errors.
954fn read(reader: &mut Reader<&[u8]>) -> Result<Event<'static>, Xform2JsonError> {
955    reader.read_event().map(Event::into_owned).map_err(xml_err)
956}
957
958/// An attribute value as an owned, entity-decoded `String`, if present.
959///
960/// Decoding matters: a recovered `&gt;` must become `>` so the forward emitter
961/// re-escapes it once (not to `&amp;gt;`), keeping round-trips byte-identical.
962fn attr(e: &quick_xml::events::BytesStart<'_>, key: &str) -> Option<String> {
963    e.attributes().flatten().find_map(|a| {
964        (local_name(a.key.as_ref()) == key).then(|| {
965            a.unescape_value()
966                .map(std::borrow::Cow::into_owned)
967                .unwrap_or_else(|_| String::from_utf8_lossy(a.value.as_ref()).into_owned())
968        })
969    })
970}
971
972fn xml_err(e: impl std::fmt::Display) -> Xform2JsonError {
973    Xform2JsonError::Xml(e.to_string())
974}
975
976#[cfg(test)]
977mod tests {
978    use super::*;
979
980    const SIMPLE: &str = r#"<?xml version="1.0"?>
981<h:html xmlns="http://www.w3.org/2002/xforms" xmlns:h="http://www.w3.org/1999/xhtml">
982  <h:head>
983    <h:title>Simple</h:title>
984    <model>
985      <instance>
986        <data id="simple"><name/><age/><meta><instanceID/></meta></data>
987      </instance>
988      <bind nodeset="/data/name" type="string"/>
989      <bind nodeset="/data/age" type="int"/>
990    </model>
991  </h:head>
992  <h:body>
993    <input ref="/data/name"><label>Your name</label></input>
994    <input ref="/data/age"><label>Your age</label></input>
995  </h:body>
996</h:html>"#;
997
998    #[test]
999    fn recovers_title_id_and_questions() {
1000        let survey = xform_to_survey(SIMPLE).unwrap();
1001        assert_eq!(survey.settings.title.as_deref(), Some("Simple"));
1002        assert_eq!(survey.settings.form_id.as_deref(), Some("simple"));
1003        assert_eq!(survey.children.len(), 2);
1004
1005        let Node::Question(q0) = &survey.children[0] else {
1006            panic!("expected question");
1007        };
1008        assert_eq!(q0.name, "name");
1009        assert_eq!(q0.label.single(), Some("Your name"));
1010        assert_eq!(q0.kind, Kind::Builtin(resolve_builtin("text").unwrap()));
1011
1012        let Node::Question(q1) = &survey.children[1] else {
1013            panic!("expected question");
1014        };
1015        assert_eq!(q1.name, "age");
1016        assert_eq!(q1.kind, Kind::Builtin(resolve_builtin("integer").unwrap()));
1017    }
1018
1019    #[test]
1020    fn recovers_select_list() {
1021        let xml = r#"<h:html xmlns:h="http://www.w3.org/1999/xhtml"><h:head><model>
1022            <bind nodeset="/data/city" type="string"/>
1023            </model></h:head><h:body>
1024            <select1 ref="/data/city"><label>City</label>
1025              <itemset nodeset="instance('cities')/root/item"><value ref="name"/></itemset>
1026            </select1></h:body></h:html>"#;
1027        let survey = xform_to_survey(xml).unwrap();
1028        let Node::Question(q) = &survey.children[0] else {
1029            panic!("expected question");
1030        };
1031        assert_eq!(
1032            q.kind,
1033            Kind::Select {
1034                select: SelectType::One,
1035                list: "cities".to_owned(),
1036                file: None,
1037            }
1038        );
1039    }
1040
1041    /// Compile markdown to an XForm, parse it back, re-emit, and return both
1042    /// XForms. They must be byte-identical for the form to round-trip.
1043    fn round_trip(md: &str) -> (String, String) {
1044        let workbook = rustxform_reader::read_markdown(md).unwrap();
1045        let survey = rustxform_parse::workbook_to_survey(&workbook).unwrap();
1046        let first = rustxform_xform::survey_to_xform(&survey).unwrap();
1047        let recovered = xform_to_survey(&first).unwrap();
1048        let second = rustxform_xform::survey_to_xform(&recovered).unwrap();
1049        (first, second)
1050    }
1051
1052    #[test]
1053    fn round_trips_forms() {
1054        let forms = [
1055            // Question types with inline labels.
1056            "| survey |\n|  | type | name | label |\n|  | text | a | A |\n\
1057             |  | integer | b | B |\n|  | decimal | c | C |\n|  | date | d | D |\n\
1058             |  | geopoint | e | E |\n|  | barcode | f | F |\n",
1059            // Logic columns, recovered as literal XPath (note the `>`).
1060            "| survey |\n|  | type | name | label | relevant | constraint | required |\n\
1061             |  | integer | age | Age |  | . > 0 | yes |\n\
1062             |  | text | nm | Nm | /data/age > 18 |  |  |\n",
1063            // Messages, hint and appearance.
1064            "| survey |\n|  | type | name | label | hint | appearance | constraint | constraint_message |\n\
1065             |  | integer | q | Q | Enter a number | multiline | . > 0 | Must be positive |\n",
1066            // A note re-emits identically (read-only string input).
1067            "| survey |\n|  | type | name | label |\n|  | note | n | Read me |\n|  | text | q | Q |\n",
1068            // A group with a sibling after it.
1069            "| survey |\n|  | type | name | label |\n|  | begin_group | g | G |\n\
1070             |  | text | x | X |\n|  | end_group |  |  |\n|  | integer | y | Y |\n",
1071            // A group carrying an appearance.
1072            "| survey |\n|  | type | name | label | appearance |\n\
1073             |  | begin_group | gp | GP | field-list |\n|  | text | z | Z |  |\n\
1074             |  | end_group |  |  |  |\n",
1075            // A counted repeat (synthesizes the `_count` calculate node).
1076            "| survey |\n|  | type | name | label | repeat_count |\n\
1077             |  | begin_repeat | rc | RC | 3 |\n|  | text | ri | RI |  |\n\
1078             |  | end_repeat |  |  |  |\n",
1079            // A repeat wrapping a nested group.
1080            "| survey |\n|  | type | name | label |\n|  | begin_repeat | r | R |\n\
1081             |  | begin_group | gg | GG |\n|  | text | yy | YY |\n|  | end_group |  |  |\n\
1082             |  | end_repeat |  |  |\n",
1083            // Inline single- and multi-select with their choice instances.
1084            "| survey |\n|  | type | name | label |\n|  | select_one yn | s1 | S1 |\n\
1085             |  | select_multiple col | s2 | S2 |\n\
1086             | choices |\n|  | list_name | name | label |\n|  | yn | y | Yes |\n\
1087             |  | yn | n | No |\n|  | col | r | Red |\n|  | col | g | Green |\n",
1088            // A data-only `calculate` node (no body control).
1089            "| survey |\n|  | type | name | label | calculation |\n\
1090             |  | integer | a | A |  |\n|  | calculate | dbl |  | ${a} * 2 |\n",
1091            // Metadata preloads interleaved with a real question.
1092            "| survey |\n|  | type | name | label |\n|  | start | start |  |\n\
1093             |  | end | end |  |\n|  | today | today |  |\n|  | deviceid | dev |  |\n\
1094             |  | text | q | Q |\n",
1095            // Multilingual label/hint + a select with multilingual choices.
1096            "| survey |\n\
1097             |  | type | name | label::English (en) | label::French (fr) | hint::English (en) | hint::French (fr) |\n\
1098             |  | text | n | Name | Nom | Enter name | Saisir le nom |\n\
1099             |  | select_one yn | c | Color | Couleur |  |  |\n\
1100             | choices |\n\
1101             |  | list_name | name | label::English (en) | label::French (fr) |\n\
1102             |  | yn | r | Red | Rouge |\n|  | yn | b | Blue | Bleu |\n\
1103             | settings |\n\
1104             |  | form_title | form_id | default_language |\n|  | F | f | English (en) |\n",
1105            // Entity create form (save_to + uuid @id + label).
1106            "| survey |\n|  | type | name | label | save_to |\n|  | text | sp | Sp | species |\n\
1107             | entities |\n|  | dataset | label |\n|  | trees | ${sp} |\n\
1108             | settings |\n|  | form_title | form_id |\n|  | F | f |\n",
1109            // Entity update form (entity_id drives base/trunk/branch versions).
1110            "| survey |\n|  | type | name | label | save_to |\n|  | text | tid | Tid |  |\n\
1111             |  | integer | c | C | circ |\n\
1112             | entities |\n|  | dataset | entity_id | label |\n|  | trees | ${tid} | ${c} |\n\
1113             | settings |\n|  | form_title | form_id |\n|  | F | f |\n",
1114            // Settings: version (on <data>), instance_name bind, style (body class).
1115            "| survey |\n|  | type | name | label |\n|  | text | q | Q |\n\
1116             | settings |\n|  | form_title | form_id | version | instance_name | style |\n\
1117             |  | F | f | 2024 | q | pages |\n",
1118            // select_one_from_file: external CSV instance, no inline choices.
1119            "| survey |\n|  | type | name | label |\n\
1120             |  | select_one_from_file cities.csv | city | City |\n\
1121             | settings |\n|  | form_title | form_id |\n|  | F | f |\n",
1122            // Multilingual constraint message (itext-referenced).
1123            "| survey |\n\
1124             |  | type | name | label::English (en) | label::French (fr) | constraint | constraint_message::English (en) | constraint_message::French (fr) |\n\
1125             |  | integer | q | Q | Q | . > 0 | Positive | Positif |\n\
1126             | settings |\n|  | form_title | form_id | default_language |\n|  | F | f | English (en) |\n",
1127            // Multilingual label media (per-language image).
1128            "| survey |\n\
1129             |  | type | name | label::English (en) | label::French (fr) | media::image::English (en) | media::image::French (fr) |\n\
1130             |  | note | p | Look | Regarde | en.png | fr.png |\n\
1131             | settings |\n|  | form_title | form_id | default_language |\n|  | F | f | English (en) |\n",
1132            // Single-language guidance hint (itext, non-multilingual).
1133            "| survey |\n|  | type | name | label | guidance_hint |\n\
1134             |  | text | q | Q | Fill it in |\n\
1135             | settings |\n|  | form_title | form_id |\n|  | F | f |\n",
1136            // Single-language label media (itext, non-multilingual).
1137            "| survey |\n|  | type | name | label | media::image |\n\
1138             |  | note | p | Look | pic.png |\n\
1139             | settings |\n|  | form_title | form_id |\n|  | F | f |\n",
1140        ];
1141        for md in forms {
1142            let (first, second) = round_trip(md);
1143            assert_eq!(first, second, "round-trip differs for form:\n{md}");
1144        }
1145    }
1146}