use std::io::{self, Read, Write};
use std::path::Path;
use std::process::ExitCode;
use std::sync::Arc;
use tabnas_alchemy::translate::Options;
use tabnas_alchemy::{canonical, format, parse_file, Input, Program, Renderer};
use tabnas_dmog::translate::{self, Document, Format};
use tabnas_transduce::{Code, Fail, Limits, Metrics, ParserSink, Sink};
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();
let worker = std::thread::Builder::new()
.name("dmog".into())
.stack_size(tabnas_alchemy::STACK_BYTES)
.spawn(move || command(&args));
match worker {
Ok(thread) => thread
.join()
.unwrap_or_else(|panic| std::panic::resume_unwind(panic)),
Err(error) => {
report(&Fail::new(
Code::ResourceLimitExceeded,
format!("no thread could be started for the command: {error}"),
));
ExitCode::from(5)
}
}
}
fn command(args: &[String]) -> ExitCode {
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)
}
}
}
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 compile(src: &str, file: &str) -> Result<Program, Fail> {
tabnas_alchemy::compile(
src,
file,
Arc::new(tabnas_transduce::routers()),
translate::renderers(),
)
}
fn compile_with(src: &str, file: &str, input: Input) -> Result<Program, Fail> {
tabnas_alchemy::compile_with(
src,
file,
input,
Arc::new(tabnas_transduce::routers()),
translate::renderers(),
)
}
fn usage() -> Exit {
Exit {
fail: Fail::input(USAGE),
status: 2,
}
}
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,
}),
}
}
fn unreadable(file: &str, fail: Fail) -> Exit {
match translate::unreadable(&fail) {
Some(reason) => {
let cannot = Fail::input(format!("cannot read {file}: {reason}"));
Exit {
fail: if fail.committed_output {
cannot.committed()
} else {
cannot
},
status: 2,
}
}
None => Exit::from(fail),
}
}
fn run(args: &[String]) -> Result<String, Exit> {
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 src = read(file)?;
match command.as_str() {
"canon" => {
let text = canonical(&parse_file(&src, file)?);
Ok(if text.is_empty() { text } else { text + "\n" })
}
"format" => Ok(format(&parse_file(&src, file)?)),
"check" => Ok(compile(&src, file).map(|_| String::new())?),
_ => Ok(compile(&src, file).map(|program| program.explain())?),
}
}
"run" => {
let options = RunOptions::parse(rest)?;
let src = read(&options.program)?;
let program = match options.grammar {
Some(_) => compile_with(&src, &options.program, Input::ParserEvents)?,
None => compile(&src, &options.program)?,
};
let limits = Limits {
max_output_bytes: options.max_output_bytes,
..Limits::default()
};
let metrics = Metrics::new();
match options.grammar {
None => {
let sink = program.sink(
Box::new(io::stdout()),
options.render,
&limits,
metrics.clone(),
)?;
let input = open(&options.input)?;
execute(sink, metrics, input, limits)
.map_err(|fail| unreadable(&options.input, fail))?;
}
Some(grammar) => {
let sink = program.parser_sink(
Box::new(io::stdout()),
options.render,
&limits,
metrics.clone(),
)?;
let input = open(&options.input)?;
execute_passes(grammar, sink, metrics, input, limits)
.map_err(|fail| unreadable(&options.input, fail))?;
}
}
Ok(String::new())
}
"translate" => {
let options = TranslateOptions::parse(rest)?;
let limits = Limits {
max_output_bytes: options.max_output_bytes,
..Limits::default()
};
let path = match &options.path {
Some(text) => Some(
translate::parse_path(text, &limits)
.map_err(|fail| Exit { fail, status: 2 })?,
),
None => None,
};
let program = match &options.program {
Some(file) => Some((file.as_str(), read(file)?)),
None => None,
};
let request = translate::Request {
from: options.from,
to: options.to,
path,
options: Options {
key: options.key.unwrap_or_else(|| Options::default().key),
},
program: program.as_ref().map(|(file, text)| (*file, text.as_str())),
whole: options.whole,
limits,
};
let compiled = translate::compile(&request)?;
let document = if options.input == "-" {
Document::Reader(Box::new(io::stdin()))
} else {
Document::File(Path::new(&options.input))
};
translate::run_document(
&request,
&compiled,
document,
Box::new(io::stdout()),
Metrics::new(),
)
.map_err(|fail| unreadable(&options.input, fail))?;
Ok(String::new())
}
"formats" => {
if !rest.is_empty() {
return Err(usage());
}
Ok(translate::formats_json() + "\n")
}
_ => Err(usage()),
}
}
struct TranslateOptions {
from: &'static translate::Format,
to: &'static translate::Format,
path: Option<String>,
key: Option<String>,
program: Option<String>,
whole: bool,
max_output_bytes: Option<u64>,
input: String,
}
impl TranslateOptions {
fn parse(args: &[String]) -> Result<TranslateOptions, Exit> {
let named = |flag: &str, id: &str| {
translate::format(id).ok_or_else(|| Exit {
fail: Fail::input(format!("{flag} takes {}, not {id:?}", translate::names())),
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" => {
let n = value()?;
max_output_bytes = Some(n.parse::<u64>().map_err(|_| Exit {
fail: Fail::input(format!(
"--max-output-bytes takes a number of bytes, not {n:?}"
)),
status: 2,
})?);
}
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(TranslateOptions {
from,
to,
path,
key,
program,
whole,
max_output_bytes,
input: input.clone(),
})
}
}
struct RunOptions {
grammar: Option<&'static Format>,
render: Option<Renderer>,
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)?;
grammar = Some(translate::format(name).filter(|f| f.parses()).ok_or_else(
|| Exit {
fail: Fail::input(format!(
"--grammar takes a format whose documents are parsed \
({}), not {name:?}",
translate::parser_names()
)),
status: 2,
},
)?);
i += 2;
}
"--render" => {
let name = args.get(i + 1).ok_or_else(usage)?;
render = Some(Renderer::named(name).ok_or_else(|| 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(n.parse::<u64>().map_err(|_| Exit {
fail: Fail::input(format!(
"--max-output-bytes takes a number of bytes, not {n:?}"
)),
status: 2,
})?);
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(),
})
}
}
fn execute(
sink: Box<dyn Sink + Send>,
metrics: Arc<Metrics>,
input: Box<dyn Read + Send>,
limits: Limits,
) -> Result<(), Fail> {
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.parser_sink_into(sink, &limits, metrics.clone())?;
json.passes_from(input)
.and_then(|source| {
json.pruned(source)
.limits(limits)
.metrics(metrics.clone())
.run_boxed(head)
.0
})
.map(|_| ())
.map_err(|fail| committed(fail, &metrics))
}
fn execute_passes(
grammar: &Format,
sink: Box<dyn ParserSink + Send>,
metrics: Arc<Metrics>,
input: Box<dyn Read + Send>,
limits: Limits,
) -> Result<(), Fail> {
grammar
.passes_from(input)
.and_then(|source| {
grammar
.pruned(source)
.limits(limits)
.metrics(metrics.clone())
.run_boxed(sink)
.0
})
.map(|_| ())
.map_err(|fail| committed(fail, &metrics))
}
fn committed(fail: Fail, metrics: &Metrics) -> Fail {
if Metrics::get(&metrics.output_bytes) > 0 && !fail.committed_output {
fail.committed()
} else {
fail
}
}