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