1use crate::entry::Entry;
48use crate::error::{ErrorPath, SpecError, SpecErrorKind};
49use crate::spec::{
50 ChoiceOption, NoulCriteria, QuestionBody, QuestionKind, QuestionSet, QuestionSpec,
51};
52
53pub const MAX_CHOICE_OPTIONS: usize = 255;
56
57pub fn parse_yaml(text: &str) -> Result<QuestionSet, SpecError> {
59 let entry: Entry = serde_yaml::from_str(text).map_err(|error| {
60 let (line, column) = error
61 .location()
62 .map(|location| (Some(location.line()), Some(location.column())))
63 .unwrap_or((None, None));
64 SpecError::syntax(error.to_string(), line, column)
65 })?;
66 build_question_set(&entry)
67}
68
69pub fn parse_json(text: &str) -> Result<QuestionSet, SpecError> {
71 let entry: Entry = serde_json::from_str(text).map_err(|error| {
72 SpecError::syntax(error.to_string(), Some(error.line()), Some(error.column()))
73 })?;
74 build_question_set(&entry)
75}
76
77fn build_question_set(root: &Entry) -> Result<QuestionSet, SpecError> {
78 let root_path = ErrorPath::root();
79 let map = expect_map(
80 root,
81 &root_path,
82 "the document must be a mapping with a `questions` key",
83 )?;
84
85 reject_duplicates(map, &root_path)?;
86 let mut state = None;
87 let mut questions = None;
88 for (key, value) in map {
89 match key.as_str() {
90 "state" => state = Some(value.clone()),
91 "questions" => questions = Some(value),
92 other => {
93 return Err(SpecError::new(
94 SpecErrorKind::UnknownField,
95 root_path.key(other),
96 format!("unknown top-level field `{other}`; the document accepts only `state` and `questions`"),
97 ));
98 }
99 }
100 }
101
102 let questions_value = questions.ok_or_else(|| {
103 SpecError::new(
104 SpecErrorKind::MissingField,
105 root_path.key("questions"),
106 "the document must declare a `questions` mapping",
107 )
108 })?;
109 let questions_path = root_path.key("questions");
110 let questions_map = expect_map(
111 questions_value,
112 &questions_path,
113 "`questions` must be a mapping of question id to spec",
114 )?;
115 if questions_map.is_empty() {
116 return Err(SpecError::new(
117 SpecErrorKind::Cardinality,
118 questions_path.clone(),
119 "`questions` must declare at least one question",
120 ));
121 }
122 reject_duplicates(questions_map, &questions_path)?;
123
124 let mut parsed = Vec::with_capacity(questions_map.len());
125 for (id, value) in questions_map {
126 if id.is_empty() {
127 return Err(SpecError::new(
128 SpecErrorKind::EmptyName,
129 questions_path.clone(),
130 "question ids must be non-empty",
131 ));
132 }
133 parsed.push(build_question(id, value, &questions_path.key(id))?);
134 }
135
136 Ok(QuestionSet {
137 state,
138 questions: parsed,
139 })
140}
141
142fn build_question(id: &str, value: &Entry, path: &ErrorPath) -> Result<QuestionSpec, SpecError> {
143 let map = expect_map(
144 value,
145 path,
146 "a question spec must be a mapping with `type` and (for choice/score) `criteria`",
147 )?;
148 reject_duplicates(map, path)?;
149
150 let mut type_tag = None;
151 let mut instructions = None;
152 let mut criteria = None;
153 for (key, field) in map {
154 match key.as_str() {
155 "type" => type_tag = Some(field),
156 "instructions" => instructions = Some(field),
157 "criteria" => criteria = Some(field),
158 other => {
159 return Err(SpecError::new(
160 SpecErrorKind::UnknownField,
161 path.key(other),
162 format!(
163 "unknown field `{other}`; question specs accept only `type`, `instructions`, and `criteria`"
164 ),
165 ));
166 }
167 }
168 }
169
170 let type_path = path.key("type");
171 let type_value = type_tag.ok_or_else(|| {
172 SpecError::new(
173 SpecErrorKind::MissingField,
174 type_path.clone(),
175 "every question requires a `type` (`noul`, `choice`, or `score`)",
176 )
177 })?;
178 let tag = match type_value {
179 Entry::Str(tag) => tag.as_str(),
180 _ => {
181 return Err(SpecError::new(
182 SpecErrorKind::Structure,
183 type_path,
184 "`type` must be a string (`noul`, `choice`, or `score`)",
185 ));
186 }
187 };
188 let kind = match QuestionKind::from_tag(tag) {
189 Some(kind) if kind.is_v1() => kind,
190 Some(reserved) => {
191 return Err(SpecError::new(
192 SpecErrorKind::ReservedQuestionType,
193 type_path,
194 format!(
195 "`{}` is reserved for profile v2 and is not implemented by schema v1",
196 reserved.as_str()
197 ),
198 ));
199 }
200 None => {
201 return Err(SpecError::new(
202 SpecErrorKind::UnknownQuestionType,
203 type_path,
204 format!("unknown question type `{tag}`; expected `noul`, `choice`, or `score`"),
205 ));
206 }
207 };
208
209 let instructions = instructions.and_then(|entry| match entry {
211 Entry::Null => None,
212 other => Some(other.clone()),
213 });
214
215 let criteria_path = path.key("criteria");
216 let body = match kind {
217 QuestionKind::Noul => QuestionBody::Noul {
218 criteria: build_noul_criteria(criteria, &criteria_path)?,
219 },
220 QuestionKind::Choice => QuestionBody::Choice {
221 options: build_choice_options(criteria, &criteria_path)?,
222 },
223 QuestionKind::Score => QuestionBody::Score {
224 levels: build_score_levels(criteria, &criteria_path)?,
225 },
226 QuestionKind::Span | QuestionKind::Derived => unreachable!("reserved kinds rejected above"),
227 };
228
229 Ok(QuestionSpec {
230 id: id.to_owned(),
231 kind,
232 instructions,
233 body,
234 })
235}
236
237fn build_noul_criteria(
238 criteria: Option<&Entry>,
239 path: &ErrorPath,
240) -> Result<Option<NoulCriteria>, SpecError> {
241 let Some(entry) = criteria else {
242 return Ok(None);
243 };
244 if matches!(entry, Entry::Null) {
245 return Ok(None);
246 }
247 let map = expect_map(
248 entry,
249 path,
250 "noul `criteria` must be a mapping with optional `true`/`false` keys",
251 )?;
252 reject_duplicates(map, path)?;
253 let mut parsed = NoulCriteria::default();
254 for (key, value) in map {
255 let entry = match value {
256 Entry::Null => None,
257 other => Some(other.clone()),
258 };
259 match key.as_str() {
260 "true" => parsed.on_true = entry,
261 "false" => parsed.on_false = entry,
262 other => {
263 return Err(SpecError::new(
264 SpecErrorKind::UnknownField,
265 path.key(other),
266 format!("noul criteria accept only the keys `true` and `false`, got `{other}`"),
267 ));
268 }
269 }
270 }
271 Ok(Some(parsed))
272}
273
274fn build_choice_options(
275 criteria: Option<&Entry>,
276 path: &ErrorPath,
277) -> Result<Vec<ChoiceOption>, SpecError> {
278 let entry = criteria.ok_or_else(|| {
279 SpecError::new(
280 SpecErrorKind::MissingField,
281 path.clone(),
282 "choice questions require a `criteria` mapping of option name to rubric",
283 )
284 })?;
285 let map = expect_map(
286 entry,
287 path,
288 "choice `criteria` must be a mapping of option name to rubric",
289 )?;
290 if map.len() < 2 {
292 return Err(SpecError::new(
293 SpecErrorKind::Cardinality,
294 path.clone(),
295 format!(
296 "choice questions need at least 2 options, got {}",
297 map.len()
298 ),
299 ));
300 }
301 if map.len() > MAX_CHOICE_OPTIONS {
302 return Err(SpecError::new(
303 SpecErrorKind::Cardinality,
304 path.clone(),
305 format!(
306 "choice questions support at most {MAX_CHOICE_OPTIONS} options, got {}; \
307 above the limit, use the two-stage score-then-choice recipe",
308 map.len()
309 ),
310 ));
311 }
312 reject_duplicates(map, path)?;
313 let mut options = Vec::with_capacity(map.len());
314 for (name, rubric) in map {
315 if name.is_empty() {
316 return Err(SpecError::new(
317 SpecErrorKind::EmptyName,
318 path.clone(),
319 "choice option names must be non-empty",
320 ));
321 }
322 options.push(ChoiceOption {
323 name: name.clone(),
324 rubric: match rubric {
325 Entry::Null => None,
326 other => Some(other.clone()),
327 },
328 });
329 }
330 Ok(options)
331}
332
333fn build_score_levels(
334 criteria: Option<&Entry>,
335 path: &ErrorPath,
336) -> Result<Vec<Option<Entry>>, SpecError> {
337 let entry = criteria.ok_or_else(|| {
338 SpecError::new(
339 SpecErrorKind::MissingField,
340 path.clone(),
341 "score questions require a `criteria` array of ordered level rubrics",
342 )
343 })?;
344 let Entry::Seq(items) = entry else {
345 return Err(SpecError::new(
346 SpecErrorKind::Structure,
347 path.clone(),
348 "score `criteria` must be an array of ordered level rubrics (index = level, 0-based)",
349 ));
350 };
351 if items.len() < 2 {
353 return Err(SpecError::new(
354 SpecErrorKind::Cardinality,
355 path.clone(),
356 format!(
357 "score questions need at least 2 levels, got {}",
358 items.len()
359 ),
360 ));
361 }
362 Ok(items
363 .iter()
364 .map(|item| match item {
365 Entry::Null => None,
366 other => Some(other.clone()),
367 })
368 .collect())
369}
370
371fn expect_map<'a>(
372 entry: &'a Entry,
373 path: &ErrorPath,
374 message: &str,
375) -> Result<&'a [(String, Entry)], SpecError> {
376 match entry {
377 Entry::Map(pairs) => Ok(pairs),
378 _ => Err(SpecError::new(
379 SpecErrorKind::Structure,
380 path.clone(),
381 message,
382 )),
383 }
384}
385
386fn reject_duplicates(map: &[(String, Entry)], path: &ErrorPath) -> Result<(), SpecError> {
387 for (index, (key, _)) in map.iter().enumerate() {
388 if map[..index].iter().any(|(earlier, _)| earlier == key) {
389 return Err(SpecError::new(
390 SpecErrorKind::DuplicateKey,
391 path.key(key),
392 format!("duplicate key `{key}`"),
393 ));
394 }
395 }
396 Ok(())
397}