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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! The `dmog` command (data mogrify), built on the `tabnas_dmog` library.
//!
//! ```text
//! dmog canon FILE       print the program in canonical form
//! dmog format FILE      print the program in layout form
//! dmog check FILE       parse, desugar, resolve, check and build the plan; print nothing and exit 0
//! dmog explain FILE     print the plan report
//! dmog run [--grammar FORMAT] [--render csv|json] [--max-output-bytes N] PROGRAM INPUT
//!                       run the program over the JSON document INPUT
//! dmog translate --from FORMAT --to FORMAT [--path PATH] [--key KEY]
//!                [--with PROGRAM] [--whole] [--max-output-bytes N] INPUT
//!                       write INPUT, read as FORMAT, in another format
//! dmog formats          print the formats translate reads and writes, as JSON
//! ```
//!
//! `FILE`, `PROGRAM` and `INPUT` may be `-` for standard input (one of
//! them per run). Nothing but the answer goes to standard output. A
//! failure is the `Fail` as one JSON object on standard error (`code`,
//! `message`, and `path`, `limit`, `row`, `col` when they apply, and
//! `output`: `"partial"` when bytes had reached standard output). The
//! exit status follows the code: 2 for a program that does not read,
//! resolve or check (`DSL_PARSE_ERROR`, `DSL_TYPE_ERROR`, `STREAM_REUSED`,
//! `STREAMABILITY_UNKNOWN`), for a usage error and for an unreadable
//! file; 1 for an input or protocol failure (from `check` too, when
//! building the plan reaches a `fail`); 5 for `RESOURCE_LIMIT_EXCEEDED`;
//! 3 for `OUTPUT_FAILED`; 6 for `ABORTED`. A standard error that cannot
//! be written loses the report, not the status.
//!
//! The command is the library's first user, and keeps only what is a
//! command's: the command line and its usage, the files and standard
//! input, and the failure's report and exit status. Every command is one
//! call of the library: `canon`, `format`, `check` and `explain` the
//! functions of those names over PROGRAM's [`Source`]; `run` a [`Program`]
//! over INPUT, its options the [`ProgramOptions`]; `translate` a
//! [`Translation`] over INPUT, its options the [`TranslateOptions`]; and
//! `formats` [`formats_json`]. INPUT is handed to the run as a reader, so
//! the output is written as it is read. A bad option is refused before
//! PROGRAM is read, as a usage error: a `--from` or `--to` that
//! [`formats`] does not list, or a `--grammar` that [`parsed_formats`]
//! does not, where the option appears, and a `--path` the library refuses.
//! INPUT the run cannot read is refused as a file that cannot be read,
//! with any output it had written.

use std::io::{self, Read, Write};
use std::process::ExitCode;

use tabnas_dmog::{
    canon, check, default_limits, explain, formats, formats_json, parsed_formats, Code, Fail,
    Limits, Program, ProgramOptions, Render, Source, TranslateOptions, Translation,
};

/// This crate's version, read from `rs/Cargo.toml`. It MUST equal
/// `ts/package.json` "version": admin/publish.sh rewrites both, and
/// `rs/tests/version_test.rs` fails the build if they drift.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

const USAGE: &str = "usage: dmog canon|format|check|explain FILE\n       dmog run [--grammar FORMAT] [--render csv|json] [--max-output-bytes N] PROGRAM INPUT\n       dmog translate --from FORMAT --to FORMAT [--path PATH] [--key KEY] [--with PROGRAM] [--whole] [--max-output-bytes N] INPUT\n       dmog formats\n       (a FILE may be - for standard input)";

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    match run(&args) {
        Ok(text) => {
            let mut out = io::stdout().lock();
            if out
                .write_all(text.as_bytes())
                .and_then(|()| out.flush())
                .is_err()
            {
                return ExitCode::from(3);
            }
            ExitCode::SUCCESS
        }
        Err(exit) => {
            report(&exit.fail);
            ExitCode::from(exit.status)
        }
    }
}

/// `eprintln!` would panic on a closed standard error, and exit 101 in
/// place of the failure's own status.
fn report(fail: &Fail) {
    let mut err = io::stderr().lock();
    let _ = writeln!(err, "{}", fail.to_json()).and_then(|()| err.flush());
}

struct Exit {
    fail: Fail,
    status: u8,
}

impl From<Fail> for Exit {
    fn from(fail: Fail) -> Exit {
        let status = match fail.code {
            Code::DslParseError
            | Code::DslTypeError
            | Code::StreamReused
            | Code::StreamabilityUnknown => 2,
            Code::ResourceLimitExceeded => 5,
            Code::OutputFailed => 3,
            Code::Aborted => 6,
            _ => 1,
        };
        Exit { fail, status }
    }
}

fn usage() -> Exit {
    Exit {
        fail: Fail::input(USAGE),
        status: 2,
    }
}

/// An option the library refused, which is the command line's fault, not
/// the document's, and so exits 2 although its code is `INPUT_INVALID`.
fn refused_option(fail: Fail) -> Exit {
    match fail.code {
        Code::InputInvalid => Exit { fail, status: 2 },
        _ => Exit::from(fail),
    }
}

fn read(file: &str) -> Result<String, Exit> {
    let mut text = String::new();
    let outcome = if file == "-" {
        io::stdin().lock().read_to_string(&mut text).map(|_| ())
    } else {
        std::fs::read_to_string(file).map(|read| text = read)
    };
    outcome.map_err(|error| Exit {
        fail: Fail::input(format!("cannot read {file}: {error}")),
        status: 2,
    })?;
    Ok(text)
}

fn open(file: &str) -> Result<Box<dyn Read + Send>, Exit> {
    if file == "-" {
        return Ok(Box::new(io::stdin()));
    }
    match std::fs::File::open(file) {
        Ok(opened) => Ok(Box::new(opened)),
        Err(error) => Err(Exit {
            fail: Fail::input(format!("cannot read {file}: {error}")),
            status: 2,
        }),
    }
}

/// A run's failure, where `file` could not be read part way, reported as
/// [`read`] reports a file it cannot read, keeping the mark of any output
/// written before it.
fn unreadable(file: &str, fail: Fail) -> Exit {
    match fail.message.strip_prefix("unreadable: ") {
        Some(reason) if fail.code == Code::InputInvalid => {
            let cannot = Fail::input(format!("cannot read {file}: {reason}"));
            Exit {
                fail: if fail.committed_output {
                    cannot.committed()
                } else {
                    cannot
                },
                status: 2,
            }
        }
        _ => Exit::from(fail),
    }
}

/// The text to print for the command line, or the failure. `run` and
/// `translate` write their answer themselves and answer nothing here.
fn run(args: &[String]) -> Result<String, Exit> {
    // The command is judged before any file is read, so an unknown one is
    // the usage error whatever the files hold, and never waits on standard
    // input to say so.
    let (command, rest) = args.split_first().ok_or_else(usage)?;
    match command.as_str() {
        "canon" | "format" | "check" | "explain" => {
            let [file] = rest else {
                return Err(usage());
            };
            let source = Source::new(file.as_str(), read(file)?);
            Ok(match command.as_str() {
                "canon" => canon(&source)?,
                "format" => tabnas_dmog::format(&source)?,
                "check" => check(&source).map(|()| String::new())?,
                _ => explain(&source)?,
            })
        }
        "run" => {
            let options = RunOptions::parse(rest)?;
            let source = Source::new(options.program.as_str(), read(&options.program)?);
            let program = Program::new(
                source,
                ProgramOptions {
                    render: options.render,
                    grammar: options.grammar,
                    limits: Limits {
                        max_output_bytes: options.max_output_bytes,
                        ..default_limits()
                    },
                },
            )?;
            let input = open(&options.input)?;
            program
                .run(input, io::stdout())
                .map_err(|fail| unreadable(&options.input, fail))?;
            Ok(String::new())
        }
        "translate" => {
            let args = TranslateArgs::parse(rest)?;
            let mut options = TranslateOptions::new(&args.from, &args.to);
            options.path = args.path;
            options.key = args.key;
            options.whole = args.whole;
            options.limits.max_output_bytes = args.max_output_bytes;
            options.validate().map_err(refused_option)?;
            if let Some(file) = &args.program {
                options.with = Some(Source::new(file.as_str(), read(file)?));
            }
            let translation = Translation::new(options)?;
            let input = open(&args.input)?;
            translation
                .run(input, io::stdout())
                .map_err(|fail| unreadable(&args.input, fail))?;
            Ok(String::new())
        }
        "formats" => {
            if !rest.is_empty() {
                return Err(usage());
            }
            Ok(formats_json() + "\n")
        }
        _ => Err(usage()),
    }
}

/// `--max-output-bytes`'s value.
fn bytes(n: &str) -> Result<u64, Exit> {
    n.parse::<u64>().map_err(|_| Exit {
        fail: Fail::input(format!(
            "--max-output-bytes takes a number of bytes, not {n:?}"
        )),
        status: 2,
    })
}

/// Format ids for a message: `abnf, c, ... or zon`.
fn names(ids: &[String]) -> String {
    match ids.split_last() {
        Some((last, [])) => last.clone(),
        Some((last, rest)) => format!("{} or {last}", rest.join(", ")),
        None => String::new(),
    }
}

struct TranslateArgs {
    from: String,
    to: String,
    path: Option<String>,
    key: Option<String>,
    program: Option<String>,
    whole: bool,
    max_output_bytes: Option<u64>,
    input: String,
}

impl TranslateArgs {
    fn parse(args: &[String]) -> Result<TranslateArgs, Exit> {
        let named = |option: &str, id: String| {
            let ids: Vec<String> = formats().into_iter().map(|format| format.id).collect();
            if ids.contains(&id) {
                return Ok(id);
            }
            Err(Exit {
                fail: Fail::input(format!("{option} takes {}, not {id:?}", names(&ids))),
                status: 2,
            })
        };
        let (mut from, mut to, mut path, mut key, mut program, mut max_output_bytes) =
            (None, None, None, None, None, None);
        let mut whole = false;
        let mut files = Vec::new();
        let mut i = 0;
        while i < args.len() {
            let value = || args.get(i + 1).cloned().ok_or_else(usage);
            match args[i].as_str() {
                "--whole" => {
                    whole = true;
                    i += 1;
                    continue;
                }
                "--from" => from = Some(named("--from", value()?)?),
                "--to" => to = Some(named("--to", value()?)?),
                "--path" => path = Some(value()?),
                "--key" => key = Some(value()?),
                "--with" => program = Some(value()?),
                "--max-output-bytes" => max_output_bytes = Some(bytes(&value()?)?),
                other if other.starts_with("--") => return Err(usage()),
                other => {
                    files.push(other.to_string());
                    i += 1;
                    continue;
                }
            }
            i += 2;
        }
        let (Some(from), Some(to), [input]) = (from, to, files.as_slice()) else {
            return Err(usage());
        };
        if program.as_deref() == Some("-") && input == "-" {
            return Err(Exit {
                fail: Fail::input("only one of PROGRAM and INPUT may be - (standard input)"),
                status: 2,
            });
        }
        Ok(TranslateArgs {
            from,
            to,
            path,
            key,
            program,
            whole,
            max_output_bytes,
            input: input.clone(),
        })
    }
}

struct RunOptions {
    grammar: Option<String>,
    render: Option<Render>,
    max_output_bytes: Option<u64>,
    program: String,
    input: String,
}

impl RunOptions {
    fn parse(args: &[String]) -> Result<RunOptions, Exit> {
        let mut grammar = None;
        let mut render = None;
        let mut max_output_bytes = None;
        let mut files = Vec::new();
        let mut i = 0;
        while i < args.len() {
            match args[i].as_str() {
                "--grammar" => {
                    let name = args.get(i + 1).ok_or_else(usage)?;
                    let parsed = parsed_formats();
                    if !parsed.contains(name) {
                        return Err(Exit {
                            fail: Fail::input(format!(
                                "--grammar takes a format whose documents are parsed ({}), not \
                                 {name:?}",
                                names(&parsed)
                            )),
                            status: 2,
                        });
                    }
                    grammar = Some(name.clone());
                    i += 2;
                }
                "--render" => {
                    let name = args.get(i + 1).ok_or_else(usage)?;
                    render = Some(match name.as_str() {
                        "csv" => Render::Csv,
                        "json" => Render::Json,
                        _ => {
                            return Err(Exit {
                                fail: Fail::input(format!(
                                    "--render takes csv or json, not {name:?}"
                                )),
                                status: 2,
                            })
                        }
                    });
                    i += 2;
                }
                "--max-output-bytes" => {
                    let n = args.get(i + 1).ok_or_else(usage)?;
                    max_output_bytes = Some(bytes(n)?);
                    i += 2;
                }
                other if other.starts_with("--") => return Err(usage()),
                other => {
                    files.push(other.to_string());
                    i += 1;
                }
            }
        }
        let [program, input] = files.as_slice() else {
            return Err(usage());
        };
        if program == "-" && input == "-" {
            return Err(Exit {
                fail: Fail::input("only one of PROGRAM and INPUT may be - (standard input)"),
                status: 2,
            });
        }
        Ok(RunOptions {
            grammar,
            render,
            max_output_bytes,
            program: program.clone(),
            input: input.clone(),
        })
    }
}