1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub enum Render {
17 Csv,
19 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#[derive(Clone, Debug, PartialEq, Eq)]
34pub struct ProgramOptions {
35 pub render: Option<Render>,
39 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 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
80pub 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 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 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 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 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 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
205fn 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
217pub 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
226pub 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
236pub fn check(source: &Source) -> Result<(), Fail> {
239 on_stack(|| compiled(source, Input::JsonEvents).map(drop))
240}
241
242pub fn explain(source: &Source) -> Result<String, Fail> {
244 on_stack(|| compiled(source, Input::JsonEvents).map(|program| program.explain()))
245}
246
247pub 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}