1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
//! Validation logic for types in [`mdbook_quiz_schema`].

#![warn(missing_docs)]

use std::{
  cell::RefCell,
  collections::HashSet,
  fmt,
  path::{Path, PathBuf},
  sync::{Arc, Mutex},
};

use mdbook_quiz_schema::*;
use miette::{
  miette, Diagnostic, EyreContext, LabeledSpan, MietteHandler, NamedSource, Result, SourceSpan,
};
use thiserror::Error;

pub use spellcheck::register_more_words;
pub use toml_spanned_value::SpannedValue;

mod impls;
mod spellcheck;

/// A thread-safe mutable set of question identifiers.
pub type IdSet = Arc<Mutex<HashSet<String>>>;

struct QuizDiagnostic {
  error: miette::Error,
  fatal: bool,
}

pub(crate) struct ValidationContext {
  diagnostics: RefCell<Vec<QuizDiagnostic>>,
  path: PathBuf,
  contents: String,
  ids: IdSet,
  spellcheck: bool,
}

impl ValidationContext {
  pub fn new(path: &Path, contents: &str, ids: IdSet, spellcheck: bool) -> Self {
    ValidationContext {
      diagnostics: Default::default(),
      path: path.to_owned(),
      contents: contents.to_owned(),
      ids,
      spellcheck,
    }
  }

  pub fn add_diagnostic(&mut self, err: impl Into<miette::Error>, fatal: bool) {
    self.diagnostics.borrow_mut().push(QuizDiagnostic {
      error: err.into(),
      fatal,
    });
  }

  pub fn error(&mut self, err: impl Into<miette::Error>) {
    self.add_diagnostic(err, true);
  }

  pub fn warning(&mut self, err: impl Into<miette::Error>) {
    self.add_diagnostic(err, false);
  }

  pub fn check(&mut self, f: impl FnOnce() -> Result<()>) {
    if let Err(res) = f() {
      self.error(res);
    }
  }

  pub fn check_id(&mut self, id: &str, value: &SpannedValue) {
    let new_id = self.ids.lock().unwrap().insert(id.to_string());
    if !new_id {
      self.error(miette!(
        labels = vec![value.labeled_span()],
        "Duplicate ID: {id}"
      ));
    }
  }

  pub fn contents(&self) -> &str {
    &self.contents
  }
}

impl fmt::Debug for ValidationContext {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    let handler = MietteHandler::default();
    for diagnostic in self.diagnostics.borrow_mut().drain(..) {
      let src = NamedSource::new(self.path.to_string_lossy(), self.contents.clone());
      let report = diagnostic.error.with_source_code(src);
      handler.debug(report.as_ref(), f)?;
    }
    Ok(())
  }
}

macro_rules! cxensure {
  ($cx:expr, $($rest:tt)*) => {{
    $cx.check(|| {
      miette::ensure!($($rest)*);
      Ok(())
    });
  }};
}

macro_rules! tomlcast {
  ($e:ident) => { $e };
  ($e:ident .table $($rest:tt)*) => {{
    let _t = $e.get_ref().as_table().unwrap();
    tomlcast!(_t $($rest)*)
  }};
  ($e:ident .array $($rest:tt)*) => {{
    let _t = $e.get_ref().as_array().unwrap();
    tomlcast!(_t $($rest)*)
  }};
  ($e:ident [$s:literal] $($rest:tt)*) => {{
    let _t = $e.get($s).unwrap();
    tomlcast!(_t $($rest)*)
  }}
}

pub(crate) use {cxensure, tomlcast};

pub(crate) trait Validate {
  fn validate(&self, cx: &mut ValidationContext, value: &SpannedValue);
}

pub(crate) trait SpannedValueExt {
  fn labeled_span(&self) -> LabeledSpan;
}

impl SpannedValueExt for SpannedValue {
  fn labeled_span(&self) -> LabeledSpan {
    let span = self.start()..self.end();
    LabeledSpan::new_with_span(None, span)
  }
}

#[derive(Error, Diagnostic, Debug)]
#[error("TOML parse error: {cause}")]
struct ParseError {
  cause: String,

  #[label]
  span: Option<SourceSpan>,
}

/// Runs validation on a quiz with TOML-format `contents` at `path` under the ID set `ids`.
pub fn validate(path: &Path, contents: &str, ids: &IdSet, spellcheck: bool) -> anyhow::Result<()> {
  let mut cx = ValidationContext::new(path, contents, Arc::clone(ids), spellcheck);

  let parse_result = toml::from_str::<Quiz>(contents);
  match parse_result {
    Ok(quiz) => {
      let value: SpannedValue = toml::from_str(contents)?;
      quiz.validate(&mut cx, &value)
    }
    Err(parse_err) => {
      let error = ParseError {
        cause: format!("{parse_err}"),
        span: None,
      };
      cx.error(error);
    }
  }

  let has_diagnostic = cx.diagnostics.borrow().len() > 0;
  let is_fatal = cx.diagnostics.borrow().iter().any(|d| d.fatal);

  if has_diagnostic {
    eprintln!("{cx:?}");
  }

  anyhow::ensure!(!is_fatal, "Quiz failed to validate: {}", path.display());

  Ok(())
}

#[cfg(test)]
pub(crate) fn harness(contents: &str) -> anyhow::Result<()> {
  validate(Path::new("dummy.rs"), contents, &IdSet::default(), true)
}

#[cfg(test)]
mod test {
  use super::*;

  #[test]
  fn validate_parse_error() {
    let contents = r#"
[[questions]]
type = "MultipleChoice
prompt.prompt = ""
answer.answer = ""
prompt.distractors = [""]
    "#;
    assert!(harness(contents).is_err());
  }
}