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
//! A document of one format written in another, as `dmog translate`
//! writes it.

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

use tabnas_alchemy::translate::Options;
use tabnas_transduce::{AbortFlag, Fail, Limits, Metrics, Segment};

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

/// What a translation reads and writes, as `dmog translate`'s options say
/// it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TranslateOptions {
    /// The format the input is read as: an id [`formats()`](crate::formats())
    /// lists.
    pub from: String,
    /// The format it is written in.
    pub to: String,
    /// A value below the root to translate instead of the whole document:
    /// a JSON array of keys and indexes, such as `["people",0]`.
    pub path: Option<String>,
    /// The member a root is wrapped under, for a format whose document must
    /// be an object; `items` when none is given. An empty key is a key:
    /// `Some(String::new())` wraps the root under `""`.
    pub key: Option<String>,
    /// A program run over the input first, whose export is written in
    /// [`to`](TranslateOptions::to).
    pub with: Option<Source>,
    /// Read the input whole, as its grammar's value, rather than streamed
    /// through its format's transducer part: for a document the part cannot
    /// stream, such as a YAML stream of several documents.
    pub whole: bool,
    pub limits: Limits,
}

impl TranslateOptions {
    /// A translation from `from` into `to`, with every other option at its
    /// default.
    pub fn new(from: &str, to: &str) -> TranslateOptions {
        TranslateOptions {
            from: from.to_string(),
            to: to.to_string(),
            path: None,
            key: None,
            with: None,
            whole: false,
            limits: default_limits(),
        }
    }

    /// The options checked as [`Translation::new`] checks them before it
    /// compiles anything: the formats are known, and the path parses. A
    /// failure is `INPUT_INVALID`.
    pub fn validate(&self) -> Result<(), Fail> {
        on_stack(|| self.resolve().map(drop))
    }

    fn resolve(&self) -> Result<Resolved, Fail> {
        let from = named("--from", &self.from)?;
        let to = named("--to", &self.to)?;
        let path = match &self.path {
            Some(text) => Some(translate::parse_path(text, &self.limits)?),
            None => None,
        };
        Ok(Resolved { from, to, path })
    }
}

struct Resolved {
    from: &'static Format,
    to: &'static Format,
    path: Option<Vec<Segment>>,
}

fn named(option: &str, id: &str) -> Result<&'static Format, Fail> {
    translate::format(id)
        .ok_or_else(|| Fail::input(format!("{option} takes {}, not {id:?}", translate::names())))
}

/// A translation compiled once, to run over many documents.
pub struct Translation {
    settings: Settings,
    compiled: Compiled,
}

/// What a [`Request`] borrows, kept for every run.
struct Settings {
    from: &'static Format,
    to: &'static Format,
    path: Option<Vec<Segment>>,
    options: Options,
    with: Option<Source>,
    whole: bool,
    limits: Limits,
}

impl Settings {
    fn request(&self) -> Request<'_> {
        Request {
            from: self.from,
            to: self.to,
            path: self.path.clone(),
            options: self.options.clone(),
            program: self
                .with
                .as_ref()
                .map(|with| (with.name.as_str(), with.text.as_str())),
            whole: self.whole,
            limits: self.limits.clone(),
        }
    }
}

impl std::fmt::Debug for Translation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Translation")
            .field("from", &self.settings.from.id())
            .field("to", &self.settings.to.id())
            .field("path", &self.settings.path)
            .field("key", &self.settings.options.key)
            .field("with", &self.settings.with.as_ref().map(|s| &s.name))
            .field("whole", &self.settings.whole)
            .finish()
    }
}

impl Translation {
    /// Compile the translation the options describe: the source format's
    /// parts, the program given `with`, and the target's, composed into
    /// one program. A route the formats cannot take is refused here,
    /// before any document is read.
    pub fn new(options: TranslateOptions) -> Result<Translation, Fail> {
        on_stack(move || {
            let Resolved { from, to, path } = options.resolve()?;
            let TranslateOptions {
                key,
                with,
                whole,
                limits,
                ..
            } = options;
            let settings = Settings {
                from,
                to,
                path,
                options: Options {
                    key: key.unwrap_or_else(|| Options::default().key),
                },
                with,
                whole,
                limits,
            };
            let compiled = translate::compile(&settings.request())?;
            Ok(Translation { settings, compiled })
        })
    }

    /// Translate what `input` gives into `output`, writing as the input is
    /// read. A failure after output was written says so
    /// ([`Fail::committed_output`]). Input that cannot be read, a reader
    /// that fails or bytes that are not UTF-8, fails as `INPUT_INVALID`
    /// with a message that starts `unreadable: `.
    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())
    }

    /// [`Translation::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)
        })
    }

    /// The translation of `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> {
        translate::run_document_with_abort(
            &self.settings.request(),
            &self.compiled,
            document,
            output,
            Metrics::new(),
            abort,
        )
    }
}

/// Translate what `input` gives into `output`, as [`Translation::run`]
/// does.
pub fn translate<R, W>(input: R, output: W, options: TranslateOptions) -> Result<(), Fail>
where
    R: Read + Send + 'static,
    W: Write + Send + 'static,
{
    Translation::new(options)?.run(input, output)
}

/// The translation of `input`, as [`Translation::run_str`] answers it.
pub fn translate_str(input: &str, options: TranslateOptions) -> Result<String, Fail> {
    Translation::new(options)?.run_str(input)
}