Skip to main content

tabnas_dmog/
program.rs

1//! An alchemy program, compiled and run over a document as `dmog run` runs
2//! it, and what `dmog canon`, `format`, `check` and `explain` print of one.
3
4use std::io::{Read, Write};
5use std::sync::Arc;
6
7use tabnas_alchemy::{Input, Renderer};
8use tabnas_transduce::{AbortFlag, Fail, Limits, Metrics};
9
10use crate::stack::{on_stack, run_on_stack, Written};
11use crate::translate::{self, Document, Format};
12use crate::{default_limits, Abort, Source};
13
14/// How a program's table or JSON events are written.
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub enum Render {
17    /// As CSV; a table's rows only.
18    Csv,
19    /// As JSON: a table as an array of records, events as their document.
20    Json,
21}
22
23impl Render {
24    fn renderer(self) -> Renderer {
25        match self {
26            Render::Csv => Renderer::Csv,
27            Render::Json => Renderer::Json,
28        }
29    }
30}
31
32/// How a program is run, as `dmog run`'s options say it.
33#[derive(Clone, Debug, PartialEq, Eq)]
34pub struct ProgramOptions {
35    /// How the export's table or JSON events are written; `None` writes a
36    /// table as CSV and events as JSON. A program that writes its own text
37    /// takes none.
38    pub render: Option<Render>,
39    /// A format whose parser reads the input, one
40    /// [`parsed_formats`](crate::parsed_formats) lists: the program reads
41    /// the parser's rule passes, as a transducer part does. `None` reads
42    /// the input as a JSON document's events.
43    pub grammar: Option<String>,
44    pub limits: Limits,
45}
46
47impl Default for ProgramOptions {
48    fn default() -> ProgramOptions {
49        ProgramOptions {
50            render: None,
51            grammar: None,
52            limits: default_limits(),
53        }
54    }
55}
56
57impl ProgramOptions {
58    /// The options checked as [`Program::new`] checks them before it
59    /// compiles the program: the grammar is a format
60    /// [`parsed_formats`](crate::parsed_formats) lists. A failure is
61    /// `INPUT_INVALID`.
62    pub fn validate(&self) -> Result<(), Fail> {
63        self.grammar_format().map(drop)
64    }
65
66    fn grammar_format(&self) -> Result<Option<&'static Format>, Fail> {
67        let Some(name) = &self.grammar else {
68            return Ok(None);
69        };
70        match translate::format(name).filter(|format| format.parses()) {
71            Some(format) => Ok(Some(format)),
72            None => Err(Fail::input(format!(
73                "--grammar takes a format whose documents are parsed ({}), not {name:?}",
74                translate::parser_names()
75            ))),
76        }
77    }
78}
79
80/// A program compiled once, to run over many documents.
81pub struct Program {
82    program: tabnas_alchemy::Program,
83    grammar: Option<&'static Format>,
84    render: Option<Renderer>,
85    limits: Limits,
86}
87
88impl std::fmt::Debug for Program {
89    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90        f.debug_struct("Program")
91            .field("file", &self.program.file())
92            .field("grammar", &self.grammar.map(Format::id))
93            .field("render", &self.render)
94            .finish()
95    }
96}
97
98impl Program {
99    /// Compile `source` to run as the options say. A program that does not
100    /// read, resolve or check is refused here, and so is a render it cannot
101    /// take, before any document is read.
102    pub fn new(source: Source, options: ProgramOptions) -> Result<Program, Fail> {
103        let grammar = options.grammar_format()?;
104        on_stack(move || {
105            let input = match grammar {
106                Some(_) => Input::ParserEvents,
107                None => Input::JsonEvents,
108            };
109            let program = compiled(&source, input)?;
110            let render = options.render.map(Render::renderer);
111            let unwritten = || Box::new(std::io::sink());
112            // Building a sink is what refuses a render the program cannot take.
113            match grammar {
114                Some(_) => drop(program.parser_sink(
115                    unwritten(),
116                    render,
117                    &options.limits,
118                    Metrics::new(),
119                )?),
120                None => drop(program.sink(unwritten(), render, &options.limits, Metrics::new())?),
121            }
122            Ok(Program {
123                program,
124                grammar,
125                render,
126                limits: options.limits,
127            })
128        })
129    }
130
131    /// Run the program over what `input` gives, writing its output to
132    /// `output` as it goes. A failure is as
133    /// [`Translation::run`](crate::Translation::run) reports one.
134    pub fn run<R, W>(&self, input: R, output: W) -> Result<(), Fail>
135    where
136        R: Read + Send + 'static,
137        W: Write + Send + 'static,
138    {
139        self.run_with_abort(input, output, &Abort::new())
140    }
141
142    /// [`Program::run`], stopped by `abort`.
143    pub fn run_with_abort<R, W>(&self, input: R, output: W, abort: &Abort) -> Result<(), Fail>
144    where
145        R: Read + Send + 'static,
146        W: Write + Send + 'static,
147    {
148        run_on_stack(abort, |flag| {
149            self.run_document(Document::Reader(Box::new(input)), Box::new(output), flag)
150        })
151    }
152
153    /// What the program writes over `input`, as a string.
154    pub fn run_str(&self, input: &str) -> Result<String, Fail> {
155        let written = Written::default();
156        let output = written.clone();
157        run_on_stack(&Abort::new(), |flag| {
158            self.run_document(Document::Text(input), Box::new(output), flag)
159        })?;
160        written.text()
161    }
162
163    fn run_document(
164        &self,
165        document: Document<'_>,
166        output: Box<dyn Write + Send>,
167        abort: &AbortFlag,
168    ) -> Result<(), Fail> {
169        let metrics = Metrics::new();
170        let program = self.program.with_abort(abort.clone());
171        let limits = &self.limits;
172        let outcome = match self.grammar {
173            Some(grammar) => program
174                .parser_sink(output, self.render, limits, metrics.clone())
175                .and_then(|sink| {
176                    translate::stream_passes(
177                        grammar,
178                        document,
179                        sink,
180                        limits,
181                        metrics.clone(),
182                        abort,
183                    )
184                }),
185            None => program
186                .sink(output, self.render, limits, metrics.clone())
187                .and_then(|sink| {
188                    let json = translate::format("json")
189                        .ok_or_else(|| Fail::input("no JSON grammar to read the input"))?;
190                    let part = json
191                        .transducer_program()?
192                        .ok_or_else(|| Fail::input("the JSON grammar ships no transducer part"))?;
193                    let head = part.with_abort(abort.clone()).parser_sink_into(
194                        sink,
195                        limits,
196                        metrics.clone(),
197                    )?;
198                    translate::stream_passes(json, document, head, limits, metrics.clone(), abort)
199                }),
200        };
201        outcome.map_err(|fail| translate::committed(fail, &metrics))
202    }
203}
204
205/// `source` compiled over `input` with transduce's routers and the
206/// renderers the command writes through.
207fn compiled(source: &Source, input: Input) -> Result<tabnas_alchemy::Program, Fail> {
208    tabnas_alchemy::compile_with(
209        &source.text,
210        &source.name,
211        input,
212        Arc::new(tabnas_transduce::routers()),
213        translate::renderers(),
214    )
215}
216
217/// The program in canonical form, as `dmog canon` prints it.
218pub fn canon(source: &Source) -> Result<String, Fail> {
219    on_stack(|| {
220        let text =
221            tabnas_alchemy::canonical(&tabnas_alchemy::parse_file(&source.text, &source.name)?);
222        Ok(if text.is_empty() { text } else { text + "\n" })
223    })
224}
225
226/// The program in layout form, as `dmog format` prints it.
227pub fn format(source: &Source) -> Result<String, Fail> {
228    on_stack(|| {
229        Ok(tabnas_alchemy::format(&tabnas_alchemy::parse_file(
230            &source.text,
231            &source.name,
232        )?))
233    })
234}
235
236/// Whether the program reads, desugars, resolves and checks, and builds
237/// its plan, as `dmog check` asks it: the failure where it does not.
238pub fn check(source: &Source) -> Result<(), Fail> {
239    on_stack(|| compiled(source, Input::JsonEvents).map(drop))
240}
241
242/// The program's plan report, as `dmog explain` prints it.
243pub fn explain(source: &Source) -> Result<String, Fail> {
244    on_stack(|| compiled(source, Input::JsonEvents).map(|program| program.explain()))
245}
246
247/// [`explain`]'s report as one JSON object.
248pub fn explain_json(source: &Source) -> Result<String, Fail> {
249    on_stack(|| {
250        compiled(source, Input::JsonEvents).map(|program| program.explain_json().to_string())
251    })
252}