Skip to main content

_native/
lib.rs

1use mdlit_core::{LitError, emit_document, parse_document, plan_all_outputs, validate_document};
2use pyo3::exceptions::PyValueError;
3use pyo3::prelude::*;
4
5fn to_python_error(error: LitError) -> PyErr {
6    PyValueError::new_err(error.to_string())
7}
8
9/// Validate and emit one Markdown document for a selected language.
10///
11/// If `language` is provided, emit only that language's output. If `None`,
12/// infer the language from the document's named blocks (requires exactly one
13/// language).
14#[pyfunction]
15#[pyo3(signature = (path, source, language=None))]
16fn emit(path: &str, source: &str, language: Option<&str>) -> PyResult<String> {
17    let document = parse_document(path, source).map_err(to_python_error)?;
18    match language {
19        Some(lang) => emit_document(&document, lang)
20            .map(|resolution| resolution.source)
21            .map_err(to_python_error),
22        None => {
23            let outputs = plan_all_outputs(&document).map_err(to_python_error)?;
24            if outputs.is_empty() {
25                return Err(PyValueError::new_err(
26                    "document has no named blocks to emit",
27                ));
28            }
29            if outputs.len() > 1 {
30                let langs: Vec<_> = outputs.iter().map(|o| o.language.as_str()).collect();
31                return Err(PyValueError::new_err(format!(
32                    "document contains multiple languages ({}); specify a language",
33                    langs.join(", ")
34                )));
35            }
36            Ok(outputs.into_iter().next().unwrap().source)
37        }
38    }
39}
40
41/// Validate one Markdown document and return warning strings.
42#[pyfunction]
43fn check(path: &str, source: &str) -> PyResult<Vec<String>> {
44    let document = parse_document(path, source).map_err(to_python_error)?;
45    validate_document(&document)
46        .map(|report| {
47            report
48                .warnings
49                .into_iter()
50                .map(|warning| warning.to_string())
51                .collect()
52        })
53        .map_err(to_python_error)
54}
55
56#[pymodule]
57fn _native(module: &Bound<'_, PyModule>) -> PyResult<()> {
58    module.add_function(wrap_pyfunction!(emit, module)?)?;
59    module.add_function(wrap_pyfunction!(check, module)?)?;
60    Ok(())
61}