rustxform_core/lib.rs
1//! Core data model shared across the rustxform pipeline.
2//!
3//! These types are the normalized, backend-agnostic representation of an
4//! XLSForm after parsing and before XForm emission. They grow as later phases
5//! add groups, repeats, translations and parameters.
6
7/// Form-level settings, sourced from the XLSForm `settings` sheet.
8#[derive(Debug, Clone, Default, PartialEq, Eq)]
9pub struct Settings {
10 /// Form identifier (`form_id`); defaults to `data` when absent.
11 pub form_id: Option<String>,
12 /// Human-readable form title.
13 pub title: Option<String>,
14 /// Form version string.
15 pub version: Option<String>,
16 /// Default language label, e.g. `French (fr)`.
17 pub default_language: Option<String>,
18 /// `instance_name` expression (populates `meta/instanceName`), if any.
19 pub instance_name: Option<String>,
20 /// `style` setting (becomes the body `class`), if any.
21 pub style: Option<String>,
22}
23
24/// Localizable text from a `label`/`hint` column family.
25///
26/// A plain `label` column fills [`default`](Self::default); language-qualified
27/// `label::Lang` columns fill [`langs`](Self::langs). The two are mutually
28/// exclusive in practice.
29#[derive(Debug, Clone, Default, PartialEq, Eq)]
30pub struct Localized {
31 /// Text from an unqualified column, if any.
32 pub default: Option<String>,
33 /// Per-language texts `(language, text)`, in language order.
34 pub langs: Vec<(String, String)>,
35}
36
37impl Localized {
38 /// `true` when no text is present at all.
39 #[must_use]
40 pub fn is_empty(&self) -> bool {
41 self.default.is_none() && self.langs.is_empty()
42 }
43
44 /// `true` when language-qualified texts are present.
45 #[must_use]
46 pub fn is_multilingual(&self) -> bool {
47 !self.langs.is_empty()
48 }
49
50 /// The unqualified single-language text, if any.
51 #[must_use]
52 pub fn single(&self) -> Option<&str> {
53 self.default.as_deref()
54 }
55
56 /// The text for a given language, if any.
57 #[must_use]
58 pub fn for_lang(&self, lang: &str) -> Option<&str> {
59 self.langs
60 .iter()
61 .find(|(l, _)| l == lang)
62 .map(|(_, t)| t.as_str())
63 }
64}
65
66/// The resolved semantics of a question's `type` column.
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub enum Kind {
69 /// A built-in type with a fixed XForm mapping.
70 Builtin(Builtin),
71 /// A `select_one` / `select_multiple` / `rank` over a choice list or file.
72 Select {
73 /// Which selection control this is.
74 select: SelectType,
75 /// The instance id: a choice-list name, or an external file's stem.
76 list: String,
77 /// External source filename for `select_*_from_file`; `None` inline.
78 file: Option<String>,
79 },
80 /// An `osm <tagset>` capture: an `osm/*` upload with tag children.
81 Osm {
82 /// Name of the tag list (from the `osm` sheet).
83 tagset: String,
84 },
85 /// A type token not yet supported; emitted as a plain string bind.
86 Unknown(String),
87}
88
89/// Which selection control a [`Kind::Select`] renders as.
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub enum SelectType {
92 /// `select_one` → `<select1>`.
93 One,
94 /// `select_multiple` → `<select>`.
95 Multiple,
96 /// `rank` → `<odk:rank>`.
97 Rank,
98}
99
100/// The XForm body control a built-in question renders as.
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102pub enum Control {
103 /// `<input>`.
104 Input,
105 /// `<range>` (uses `start`/`end`/`step` from `parameters`).
106 Range,
107 /// `<trigger>` (e.g. `acknowledge`).
108 Trigger,
109 /// `<upload>` with the given `mediatype`.
110 Upload {
111 /// The `mediatype` attribute, e.g. `image/*`.
112 mediatype: &'static str,
113 },
114}
115
116/// A metadata preload binding (`jr:preload` + `jr:preloadParams`).
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub struct Preload {
119 /// The `jr:preload` value, e.g. `timestamp` or `property`.
120 pub preload: &'static str,
121 /// The `jr:preloadParams` value, e.g. `start` or `deviceid`.
122 pub params: &'static str,
123}
124
125/// A label media attachment: a form (`image`/`audio`/`video`) and its file(s),
126/// which may be single- or multi-language.
127#[derive(Debug, Clone, PartialEq, Eq)]
128pub struct Media {
129 /// The media form: `image`, `audio` or `video`.
130 pub form: String,
131 /// Filenames, single (unqualified) or per-language.
132 pub files: Localized,
133}
134
135/// The XForm mapping for a built-in question type.
136#[derive(Debug, Clone, Copy, PartialEq, Eq)]
137pub struct Builtin {
138 /// Body control, or `None` for data-only types (`calculate`, preloads).
139 pub control: Option<Control>,
140 /// XForm bind data type (e.g. `string`, `int`, `binary`).
141 pub bind_type: &'static str,
142 /// Whether the bind is read-only.
143 pub readonly: bool,
144 /// Metadata preload, if this type is a preload.
145 pub preload: Option<Preload>,
146 /// A model-level action this type emits (e.g. `odk:recordaudio`).
147 pub action: Option<Action>,
148}
149
150/// A model-level action element bound to a question.
151#[derive(Debug, Clone, Copy, PartialEq, Eq)]
152pub struct Action {
153 /// Element name, e.g. `odk:recordaudio` or `odk:setgeopoint`.
154 pub element: &'static str,
155 /// The `event` attribute, e.g. `odk-instance-load`.
156 pub event: &'static str,
157}
158
159/// A single survey question from the `survey` sheet.
160#[derive(Debug, Clone, PartialEq, Eq)]
161pub struct Question {
162 /// Resolved type semantics.
163 pub kind: Kind,
164 /// Node name; becomes the instance element name.
165 pub name: String,
166 /// Label text (single- or multi-language).
167 pub label: Localized,
168 /// Hint text (single- or multi-language).
169 pub hint: Localized,
170 /// `appearance` column value, if any.
171 pub appearance: Option<String>,
172 /// Expression from the `calculation` column, if any.
173 pub calculation: Option<String>,
174 /// Expression from the `relevant` column, if any.
175 pub relevant: Option<String>,
176 /// Expression from the `constraint` column, if any.
177 pub constraint: Option<String>,
178 /// Raw `required` column value (e.g. `yes` or an expression), if any.
179 pub required: Option<String>,
180 /// Raw `read_only` column value, if any.
181 pub readonly: Option<String>,
182 /// `constraint_message` column (single- or multi-language).
183 pub constraint_message: Localized,
184 /// `required_message` column (single- or multi-language).
185 pub required_message: Localized,
186 /// Parsed `parameters` column, as `(key, value)` pairs.
187 pub parameters: Vec<(String, String)>,
188 /// Label media (images/audio/video), possibly per-language.
189 pub media: Vec<Media>,
190 /// Default value (`default` column), placed in the primary instance.
191 pub default: Option<String>,
192 /// `choice_filter` expression for cascading selects, if any.
193 pub choice_filter: Option<String>,
194 /// `save_to` column: the entity property this answer populates, if any.
195 pub save_to: Option<String>,
196}
197
198impl Question {
199 /// The value of a parameter from the `parameters` column, if present.
200 #[must_use]
201 pub fn parameter(&self, key: &str) -> Option<&str> {
202 self.parameters
203 .iter()
204 .find(|(k, _)| k == key)
205 .map(|(_, v)| v.as_str())
206 }
207}
208
209/// One option within a choice list.
210#[derive(Debug, Clone, PartialEq, Eq)]
211pub struct Choice {
212 /// Stored value (`name` column).
213 pub name: String,
214 /// Display label (single- or multi-language).
215 pub label: Localized,
216 /// Extra columns `(name, value)` for cascading filters, in header order.
217 pub extra: Vec<(String, String)>,
218}
219
220/// A named list of choices from the `choices` sheet.
221#[derive(Debug, Clone, PartialEq, Eq)]
222pub struct ChoiceList {
223 /// List name referenced by `select_*` questions.
224 pub name: String,
225 /// Options in sheet order.
226 pub items: Vec<Choice>,
227}
228
229/// A container of child nodes: a group (`<group>`) or a repeat (`<repeat>`).
230#[derive(Debug, Clone, PartialEq, Eq)]
231pub struct Container {
232 /// Node name; becomes the enclosing instance element.
233 pub name: String,
234 /// Default-language label, if any.
235 pub label: Option<String>,
236 /// `appearance` column value (e.g. `field-list`), if any.
237 pub appearance: Option<String>,
238 /// `repeat_count` expression (repeats only), if any.
239 pub count: Option<String>,
240 /// Ordered child nodes.
241 pub children: Vec<Node>,
242}
243
244/// A node in the survey tree: a question, a group, or a repeat.
245#[expect(
246 clippy::large_enum_variant,
247 reason = "Question is by far the most common node; boxing it would add an allocation on the common path"
248)]
249#[derive(Debug, Clone, PartialEq, Eq)]
250pub enum Node {
251 /// A leaf question.
252 Question(Question),
253 /// A non-repeating group of nodes.
254 Group(Container),
255 /// A repeating group of nodes.
256 Repeat(Container),
257}
258
259/// An ODK Entities declaration (the `entities` sheet): the survey creates an
260/// entity in a dataset when submitted.
261#[derive(Debug, Clone, PartialEq, Eq)]
262pub struct Entity {
263 /// Target dataset name.
264 pub dataset: String,
265 /// Label expression for the entity, if any.
266 pub label: Option<String>,
267 /// `entity_id` expression: present ⇒ update mode, absent ⇒ create.
268 pub entity_id: Option<String>,
269 /// `create_if` condition expression, if any.
270 pub create_if: Option<String>,
271 /// `update_if` condition expression, if any.
272 pub update_if: Option<String>,
273}
274
275/// A parsed XLSForm survey: settings, a node tree and choice lists.
276#[derive(Debug, Clone, Default, PartialEq, Eq)]
277pub struct Survey {
278 /// Form-level settings.
279 pub settings: Settings,
280 /// Ordered top-level nodes.
281 pub children: Vec<Node>,
282 /// Choice lists from the `choices` sheet.
283 pub choices: Vec<ChoiceList>,
284 /// Declared languages, in order; empty for a single-language form.
285 pub languages: Vec<String>,
286 /// Entities declaration from the `entities` sheet, if any.
287 pub entity: Option<Entity>,
288 /// Whether an `audit` metadata question is present.
289 pub audit: bool,
290 /// `xml-external` instance ids (each loads `jr://file/<id>.xml`).
291 pub external_instances: Vec<String>,
292 /// OSM tag lists from the `osm` sheet.
293 pub osm_tags: Vec<ChoiceList>,
294}
295
296impl Survey {
297 /// Return the choice list with the given name, if present.
298 #[must_use]
299 pub fn choice_list(&self, name: &str) -> Option<&ChoiceList> {
300 self.choices.iter().find(|c| c.name == name)
301 }
302}
303
304/// Resolve a single XLSForm type token to its built-in XForm mapping.
305///
306/// Returns `None` for `select_*` (handled separately) and unknown tokens.
307/// The table grows as later phases add question kinds.
308#[must_use]
309pub fn resolve_builtin(kind: &str) -> Option<Builtin> {
310 let b = |control, bind_type, readonly, preload| Builtin {
311 control,
312 bind_type,
313 readonly,
314 preload,
315 action: None,
316 };
317 let input = Some(Control::Input);
318 let preload = |preload, params| Some(Preload { preload, params });
319
320 Some(match kind {
321 "text" => b(input, "string", false, None),
322 "integer" => b(input, "int", false, None),
323 "decimal" => b(input, "decimal", false, None),
324 "range" => b(Some(Control::Range), "int", false, None),
325 "date" => b(input, "date", false, None),
326 "time" => b(input, "time", false, None),
327 "dateTime" => b(input, "dateTime", false, None),
328 "geopoint" => b(input, "geopoint", false, None),
329 "geotrace" => b(input, "geotrace", false, None),
330 "geoshape" => b(input, "geoshape", false, None),
331 "barcode" => b(input, "barcode", false, None),
332 "note" => b(input, "string", true, None),
333 "acknowledge" => b(Some(Control::Trigger), "string", false, None),
334 "image" => b(
335 Some(Control::Upload {
336 mediatype: "image/*",
337 }),
338 "binary",
339 false,
340 None,
341 ),
342 "audio" => b(
343 Some(Control::Upload {
344 mediatype: "audio/*",
345 }),
346 "binary",
347 false,
348 None,
349 ),
350 "video" => b(
351 Some(Control::Upload {
352 mediatype: "video/*",
353 }),
354 "binary",
355 false,
356 None,
357 ),
358 "file" => b(
359 Some(Control::Upload {
360 mediatype: "application/*",
361 }),
362 "binary",
363 false,
364 None,
365 ),
366 "calculate" => b(None, "string", false, None),
367 "start" => b(None, "dateTime", false, preload("timestamp", "start")),
368 "end" => b(None, "dateTime", false, preload("timestamp", "end")),
369 "today" => b(None, "date", false, preload("date", "today")),
370 "deviceid" => b(None, "string", false, preload("property", "deviceid")),
371 "username" => b(None, "string", false, preload("property", "username")),
372 "phonenumber" => b(None, "string", false, preload("property", "phonenumber")),
373 "email" => b(None, "string", false, preload("property", "email")),
374 "simserial" => b(None, "string", false, preload("property", "simserial")),
375 "subscriberid" => b(None, "string", false, preload("property", "subscriberid")),
376 "background-audio" => Builtin {
377 control: None,
378 bind_type: "binary",
379 readonly: false,
380 preload: None,
381 action: Some(Action {
382 element: "odk:recordaudio",
383 event: "odk-instance-load",
384 }),
385 },
386 "start-geopoint" => Builtin {
387 control: None,
388 bind_type: "geopoint",
389 readonly: false,
390 preload: None,
391 action: Some(Action {
392 element: "odk:setgeopoint",
393 event: "odk-instance-first-load",
394 }),
395 },
396 _ => return None,
397 })
398}