tabnas-dmog 0.4.0

The dmog library and command (data mogrify): translates a document from any tabnas format into any other, streaming, and runs alchemy programs over JSON documents, composing tabnas-alchemy, tabnas-transduce and tabnas-render.
Documentation
//! An alchemy program, compiled and run over a document as `dmog run` runs
//! it, and what `dmog canon`, `format`, `check` and `explain` print of one.

use std::io::{Read, Write};
use std::sync::Arc;

use tabnas_alchemy::{Input, Renderer};
use tabnas_transduce::{AbortFlag, Fail, Limits, Metrics};

use crate::stack::{on_stack, run_on_stack, Written};
use crate::translate::{self, Document, Format};
use crate::{default_limits, Abort, Source};

/// How a program's table or JSON events are written.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Render {
    /// As CSV; a table's rows only.
    Csv,
    /// As JSON: a table as an array of records, events as their document.
    Json,
}

impl Render {
    fn renderer(self) -> Renderer {
        match self {
            Render::Csv => Renderer::Csv,
            Render::Json => Renderer::Json,
        }
    }
}

/// How a program is run, as `dmog run`'s options say it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProgramOptions {
    /// How the export's table or JSON events are written; `None` writes a
    /// table as CSV and events as JSON. A program that writes its own text
    /// takes none.
    pub render: Option<Render>,
    /// A format whose parser reads the input, one
    /// [`parsed_formats`](crate::parsed_formats) lists: the program reads
    /// the parser's rule passes, as a transducer part does. `None` reads
    /// the input as a JSON document's events.
    pub grammar: Option<String>,
    pub limits: Limits,
}

impl Default for ProgramOptions {
    fn default() -> ProgramOptions {
        ProgramOptions {
            render: None,
            grammar: None,
            limits: default_limits(),
        }
    }
}

impl ProgramOptions {
    /// The options checked as [`Program::new`] checks them before it
    /// compiles the program: the grammar is a format
    /// [`parsed_formats`](crate::parsed_formats) lists. A failure is
    /// `INPUT_INVALID`.
    pub fn validate(&self) -> Result<(), Fail> {
        self.grammar_format().map(drop)
    }

    fn grammar_format(&self) -> Result<Option<&'static Format>, Fail> {
        let Some(name) = &self.grammar else {
            return Ok(None);
        };
        match translate::format(name).filter(|format| format.parses()) {
            Some(format) => Ok(Some(format)),
            None => Err(Fail::input(format!(
                "--grammar takes a format whose documents are parsed ({}), not {name:?}",
                translate::parser_names()
            ))),
        }
    }
}

/// A program compiled once, to run over many documents.
pub struct Program {
    program: tabnas_alchemy::Program,
    grammar: Option<&'static Format>,
    render: Option<Renderer>,
    limits: Limits,
}

impl std::fmt::Debug for Program {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Program")
            .field("file", &self.program.file())
            .field("grammar", &self.grammar.map(Format::id))
            .field("render", &self.render)
            .finish()
    }
}

impl Program {
    /// Compile `source` to run as the options say. A program that does not
    /// read, resolve or check is refused here, and so is a render it cannot
    /// take, before any document is read.
    pub fn new(source: Source, options: ProgramOptions) -> Result<Program, Fail> {
        let grammar = options.grammar_format()?;
        on_stack(move || {
            let input = match grammar {
                Some(_) => Input::ParserEvents,
                None => Input::JsonEvents,
            };
            let program = compiled(&source, input)?;
            let render = options.render.map(Render::renderer);
            let unwritten = || Box::new(std::io::sink());
            // Building a sink is what refuses a render the program cannot take.
            match grammar {
                Some(_) => drop(program.parser_sink(
                    unwritten(),
                    render,
                    &options.limits,
                    Metrics::new(),
                )?),
                None => drop(program.sink(unwritten(), render, &options.limits, Metrics::new())?),
            }
            Ok(Program {
                program,
                grammar,
                render,
                limits: options.limits,
            })
        })
    }

    /// Run the program over what `input` gives, writing its output to
    /// `output` as it goes. A failure is as
    /// [`Translation::run`](crate::Translation::run) reports one.
    pub fn run<R, W>(&self, input: R, output: W) -> Result<(), Fail>
    where
        R: Read + Send + 'static,
        W: Write + Send + 'static,
    {
        self.run_with_abort(input, output, &Abort::new())
    }

    /// [`Program::run`], stopped by `abort`.
    pub fn run_with_abort<R, W>(&self, input: R, output: W, abort: &Abort) -> Result<(), Fail>
    where
        R: Read + Send + 'static,
        W: Write + Send + 'static,
    {
        run_on_stack(abort, |flag| {
            self.run_document(Document::Reader(Box::new(input)), Box::new(output), flag)
        })
    }

    /// What the program writes over `input`, as a string.
    pub fn run_str(&self, input: &str) -> Result<String, Fail> {
        let written = Written::default();
        let output = written.clone();
        run_on_stack(&Abort::new(), |flag| {
            self.run_document(Document::Text(input), Box::new(output), flag)
        })?;
        written.text()
    }

    fn run_document(
        &self,
        document: Document<'_>,
        output: Box<dyn Write + Send>,
        abort: &AbortFlag,
    ) -> Result<(), Fail> {
        let metrics = Metrics::new();
        let program = self.program.with_abort(abort.clone());
        let limits = &self.limits;
        let outcome = match self.grammar {
            Some(grammar) => program
                .parser_sink(output, self.render, limits, metrics.clone())
                .and_then(|sink| {
                    translate::stream_passes(
                        grammar,
                        document,
                        sink,
                        limits,
                        metrics.clone(),
                        abort,
                    )
                }),
            None => program
                .sink(output, self.render, limits, metrics.clone())
                .and_then(|sink| {
                    let json = translate::format("json")
                        .ok_or_else(|| Fail::input("no JSON grammar to read the input"))?;
                    let part = json
                        .transducer_program()?
                        .ok_or_else(|| Fail::input("the JSON grammar ships no transducer part"))?;
                    let head = part.with_abort(abort.clone()).parser_sink_into(
                        sink,
                        limits,
                        metrics.clone(),
                    )?;
                    translate::stream_passes(json, document, head, limits, metrics.clone(), abort)
                }),
        };
        outcome.map_err(|fail| translate::committed(fail, &metrics))
    }
}

/// `source` compiled over `input` with transduce's routers and the
/// renderers the command writes through.
fn compiled(source: &Source, input: Input) -> Result<tabnas_alchemy::Program, Fail> {
    tabnas_alchemy::compile_with(
        &source.text,
        &source.name,
        input,
        Arc::new(tabnas_transduce::routers()),
        translate::renderers(),
    )
}

/// The program in canonical form, as `dmog canon` prints it.
pub fn canon(source: &Source) -> Result<String, Fail> {
    on_stack(|| {
        let text =
            tabnas_alchemy::canonical(&tabnas_alchemy::parse_file(&source.text, &source.name)?);
        Ok(if text.is_empty() { text } else { text + "\n" })
    })
}

/// The program in layout form, as `dmog format` prints it.
pub fn format(source: &Source) -> Result<String, Fail> {
    on_stack(|| {
        Ok(tabnas_alchemy::format(&tabnas_alchemy::parse_file(
            &source.text,
            &source.name,
        )?))
    })
}

/// Whether the program reads, desugars, resolves and checks, and builds
/// its plan, as `dmog check` asks it: the failure where it does not.
pub fn check(source: &Source) -> Result<(), Fail> {
    on_stack(|| compiled(source, Input::JsonEvents).map(drop))
}

/// The program's plan report, as `dmog explain` prints it.
pub fn explain(source: &Source) -> Result<String, Fail> {
    on_stack(|| compiled(source, Input::JsonEvents).map(|program| program.explain()))
}

/// [`explain`]'s report as one JSON object.
pub fn explain_json(source: &Source) -> Result<String, Fail> {
    on_stack(|| {
        compiled(source, Input::JsonEvents).map(|program| program.explain_json().to_string())
    })
}