use std::io::{Read, Write};
use std::path::Path;
use std::sync::{Arc, OnceLock};
use tabnas_alchemy::shared::{CsvOptions, JoinOut, JsonOptions, Renderers, TableSink, TextOut};
use tabnas_alchemy::translate::{
compose, compose_parsed, compose_program, compose_program_parsed, Alc, Composition, Descriptor,
Front, Options, Part, PartText, Render, Root, Shape,
};
use tabnas_alchemy::{Input, Output, Program, Source};
use tabnas_transduce::{
capability, walk_datum, AbortFlag, Code, Datum, DatumBuilder, Duplicates, Fail, Flow, Guarded,
JsonEvent, Limits, Metrics, ParserEventSource, ParserSource, Segment, Sink, TreeContract,
};
pub fn renderers() -> Arc<dyn Renderers> {
Arc::new(CommandRenderers(tabnas_render::renderers()))
}
struct CommandRenderers(tabnas_render::RenderRenderers);
impl Renderers for CommandRenderers {
fn json(&self, out: Box<dyn TextOut + Send>, options: JsonOptions) -> Box<dyn Sink + Send> {
self.0.json(out, options)
}
fn csv(
&self,
out: Box<dyn TextOut + Send>,
options: CsvOptions,
) -> Result<Box<dyn TableSink + Send>, Fail> {
self.0.csv(out, options)
}
fn records_to_json(&self, sink: Box<dyn Sink + Send>) -> Box<dyn TableSink + Send> {
self.0.records_to_json(sink)
}
fn join<'a>(
&self,
out: Box<dyn TextOut + Send + 'a>,
separator: &str,
) -> Box<dyn JoinOut + Send + 'a> {
self.0.join(out, separator)
}
fn replace_text<'a>(
&self,
out: Box<dyn TextOut + Send + 'a>,
from: &str,
to: &str,
) -> Box<dyn TextOut + Send + 'a> {
self.0.replace_text(out, from, to)
}
fn write_out(
&self,
writer: Box<dyn Write + Send>,
limits: &Limits,
metrics: Arc<Metrics>,
) -> Box<dyn TextOut + Send> {
Box::new(
tabnas_render::WriteOut::new(writer)
.with_limits(limits)
.with_metrics(metrics)
.with_hold(tabnas_render::DEFAULT_BUDGET),
)
}
}
#[derive(Clone, Copy)]
struct Parsing {
events: for<'s> fn(&'s str) -> ParserSource<'s>,
passes: for<'s> fn(&'s str) -> ParserEventSource<'s>,
reads: fn(Box<dyn Read + Send>) -> ParserEventSource<'static>,
}
#[derive(Clone, Copy)]
enum Reader {
Parser(Parsing),
Checked(Check, Parsing),
Tree(fn(&str) -> Result<Datum, Fail>),
ParsedTree(Parsing, fn(&str) -> Result<Datum, Fail>),
}
type Bytes = Box<dyn Read + Send>;
#[derive(Clone, Copy)]
struct Check {
text: fn(&str) -> Result<(), Fail>,
reader: fn(Bytes) -> Result<Bytes, Fail>,
}
pub struct Format {
pub part: Part,
reader: Reader,
transducer: Option<Alc>,
compiled: OnceLock<Result<Option<Program>, Fail>>,
}
impl Format {
pub fn id(&self) -> &str {
&self.part.id
}
pub fn transducer(&self) -> Option<&Alc> {
self.transducer.as_ref()
}
pub fn parses(&self) -> bool {
!matches!(self.reader, Reader::Tree(_))
}
pub fn passes<'s>(&self, text: &'s str) -> Result<ParserEventSource<'s>, Fail> {
match self.reader {
Reader::Parser(parsing) | Reader::ParsedTree(parsing, _) => Ok((parsing.passes)(text)),
Reader::Checked(check, parsing) => (check.text)(text).map(|()| (parsing.passes)(text)),
Reader::Tree(_) => Err(self.no_passes()),
}
}
pub fn passes_from(
&self,
reader: Box<dyn Read + Send>,
) -> Result<ParserEventSource<'static>, Fail> {
match self.reader {
Reader::Parser(parsing) | Reader::ParsedTree(parsing, _) => Ok((parsing.reads)(reader)),
Reader::Checked(check, parsing) => Ok((parsing.reads)((check.reader)(reader)?)),
Reader::Tree(_) => Err(self.no_passes()),
}
}
pub fn pruned<'s>(&self, source: ParserEventSource<'s>) -> ParserEventSource<'s> {
if capability::prunable(self.id()) {
source.grammar(self.id()).prune()
} else {
source
}
}
fn no_passes(&self) -> Fail {
Fail::input(format!(
"{} is read as a tree, not parsed: it has no rule passes for a program to read",
self.id()
))
}
pub fn transducer_program(&self) -> Result<Option<Program>, Fail> {
self.compiled
.get_or_init(|| {
let Some(alc) = &self.transducer else {
return Ok(None);
};
let main = format!("def export [input] ({} input)", alc.entry);
let sources = [
Source::new(&alc.file, &alc.text),
Source::new("main", &main),
];
tabnas_alchemy::compile_sources_with(
&sources,
Input::ParserEvents,
Arc::new(tabnas_transduce::routers()),
renderers(),
)
.map(Some)
})
.clone()
}
pub fn read(&self, input: &str, limits: &Limits) -> Result<Datum, Fail> {
if let Some(part) = self.transducer_program()? {
match read_through(self, &part, input, limits) {
Err(fail) if unfollowed(&fail) => {}
outcome => return outcome,
}
}
read(self, input, limits)
}
}
struct Described {
descriptor: Descriptor,
transduce: Option<PartText>,
}
macro_rules! descriptor {
($package:literal, $module:ident) => {
$module::translate().map(|parts| Described {
descriptor: Descriptor {
package: $package.to_string(),
manifest: parts.manifest.to_string(),
lift: parts.lift.map(|p| PartText::new(p.entry, p.source)),
embed: None,
render: parts.render.map(|p| PartText::new(p.entry, p.source)),
},
transduce: None,
})
};
($package:literal, $module:ident, embed) => {
$module::translate().map(|parts| Described {
descriptor: Descriptor {
package: $package.to_string(),
manifest: parts.manifest.to_string(),
lift: parts.lift.map(|p| PartText::new(p.entry, p.source)),
embed: parts.embed.map(|p| PartText::new(p.entry, p.source)),
render: parts.render.map(|p| PartText::new(p.entry, p.source)),
},
transduce: None,
})
};
($package:literal, $module:ident, transduce) => {
$module::translate().map(|parts| Described {
descriptor: Descriptor {
package: $package.to_string(),
manifest: parts.manifest.to_string(),
lift: parts.lift.map(|p| PartText::new(p.entry, p.source)),
embed: None,
render: parts.render.map(|p| PartText::new(p.entry, p.source)),
},
transduce: parts.transduce.map(|p| PartText::new(p.entry, p.source)),
})
};
($package:literal, $module:ident, embed, transduce) => {
$module::translate().map(|parts| Described {
descriptor: Descriptor {
package: $package.to_string(),
manifest: parts.manifest.to_string(),
lift: parts.lift.map(|p| PartText::new(p.entry, p.source)),
embed: parts.embed.map(|p| PartText::new(p.entry, p.source)),
render: parts.render.map(|p| PartText::new(p.entry, p.source)),
},
transduce: parts.transduce.map(|p| PartText::new(p.entry, p.source)),
})
};
}
macro_rules! parsing {
($make:expr) => {{
fn events(text: &str) -> ParserSource<'_> {
ParserSource::new($make, text)
}
fn passes(text: &str) -> ParserEventSource<'_> {
ParserEventSource::new($make, text)
}
fn reads(reader: Box<dyn Read + Send>) -> ParserEventSource<'static> {
ParserEventSource::from_reader($make, reader)
}
Parsing {
events,
passes,
reads,
}
}};
}
macro_rules! reader {
($module:ident) => {
Reader::Parser(parsing!($module::make()))
};
}
fn read_pgn() -> Reader {
Reader::Parser(parsing!(tabnas_chess::make(
&tabnas_chess::ChessOptions::default()
)
.unwrap_or_else(|e| panic!(
"tabnas-chess: the grammar does not install: {e}"
))))
}
fn json5_value_check(text: &str) -> Result<(), Fail> {
let rest = text.trim_start_matches(|c: char| c.is_whitespace() || c == '\u{feff}');
if !(rest.is_empty() || rest.starts_with('/')) {
return Ok(());
}
match tabnas_json5::parse_with(&tabnas_json5::make(), text) {
Err(error) if error.code == "json5_empty" || error.code == "json5_no_value" => {
Err(Fail::from_tabnas(&error))
}
_ => Ok(()),
}
}
fn json5_reader_check(reader: Bytes) -> Result<Bytes, Fail> {
match tabnas_json5::check_reader(&tabnas_json5::make(), reader) {
Ok(checked) => Ok(Box::new(checked)),
Err(error) => Err(Fail::from_tabnas(&error)),
}
}
fn read_json5() -> Reader {
Reader::Checked(
Check {
text: json5_value_check,
reader: json5_reader_check,
},
parsing!(tabnas_json5::make()),
)
}
fn engine_failure(error: &tabnas_json::JsonError) -> Fail {
let mut fail = Fail::from_tabnas(error);
if error.code == "cancel" {
fail.message = format!(
"the grammar stopped the parse with a guard of its own ({}: {}); a grammar \
may refuse nesting or size below this crate's Limits",
error.code,
error.detail.trim_end()
);
}
fail
}
fn read_expr(text: &str) -> Result<Datum, Fail> {
tabnas_expr::parse_simplified(&tabnas_expr::make(), text)
.map(|tree| Datum::from_tabnas(&tree))
.map_err(|error| engine_failure(&error))
}
fn read_proto(text: &str) -> Result<Datum, Fail> {
tabnas_proto::parse_tree(text)
.map(|tree| Datum::from_tabnas(&tree))
.map_err(proto_failure)
}
fn proto_failure(error: tabnas_proto::ProtoError) -> Fail {
match error {
tabnas_proto::ProtoError::Parse(error) => engine_failure(&error),
refused => Fail::input(refused.to_string()),
}
}
fn read_proto_parsed() -> Reader {
Reader::ParsedTree(parsing!(tabnas_proto::make_streaming()), read_proto)
}
fn read_c(text: &str) -> Result<Datum, Fail> {
tabnas_c::parse(text)
.map(|tree| Datum::from_tabnas(&tree))
.map_err(|error| engine_failure(&error))
}
fn read_c_parsed() -> Reader {
Reader::ParsedTree(parsing!(tabnas_c::make_streaming()), read_c)
}
fn packages() -> Vec<(Option<Described>, Reader)> {
vec![
(
descriptor!("tabnas-abnf", tabnas_abnf, embed, transduce),
reader!(tabnas_abnf),
),
(
descriptor!("tabnas-c", tabnas_c, embed, transduce),
read_c_parsed(),
),
(
descriptor!("tabnas-chess", tabnas_chess, embed, transduce),
read_pgn(),
),
(
descriptor!("tabnas-css", tabnas_css, embed, transduce),
reader!(tabnas_css),
),
(
descriptor!("tabnas-csv", tabnas_csv, embed, transduce),
reader!(tabnas_csv),
),
(
descriptor!("tabnas-ebnf", tabnas_ebnf, embed, transduce),
reader!(tabnas_ebnf),
),
(
descriptor!("tabnas-expr", tabnas_expr, embed),
Reader::Tree(read_expr),
),
(
descriptor!("tabnas-feed", tabnas_feed, embed, transduce),
reader!(tabnas_feed),
),
(
descriptor!("tabnas-gbnf", tabnas_gbnf, embed, transduce),
reader!(tabnas_gbnf),
),
(
descriptor!("tabnas-ini", tabnas_ini, embed, transduce),
reader!(tabnas_ini),
),
(
descriptor!("tabnas-json", tabnas_json, embed, transduce),
reader!(tabnas_json),
),
(
descriptor!("tabnas-json5", tabnas_json5, embed, transduce),
read_json5(),
),
(
descriptor!("tabnas-jsonc", tabnas_jsonc, embed, transduce),
reader!(tabnas_jsonc),
),
(
descriptor!("tabnas-jsonic", tabnas_jsonic, embed, transduce),
reader!(tabnas_jsonic),
),
(
descriptor!("tabnas-jsonl", tabnas_jsonl, embed, transduce),
reader!(tabnas_jsonl),
),
(
descriptor!("tabnas-markdown", tabnas_markdown, embed, transduce),
reader!(tabnas_markdown),
),
(
descriptor!("tabnas-proto", tabnas_proto, embed, transduce),
read_proto_parsed(),
),
(
descriptor!("tabnas-semver", tabnas_semver, embed),
reader!(tabnas_semver),
),
(
descriptor!("tabnas-toml", tabnas_toml, embed, transduce),
reader!(tabnas_toml),
),
(
descriptor!("tabnas-xml", tabnas_xml, embed, transduce),
reader!(tabnas_xml),
),
(
descriptor!("tabnas-yaml", tabnas_yaml, transduce),
reader!(tabnas_yaml),
),
(
descriptor!("tabnas-zon", tabnas_zon, transduce),
reader!(tabnas_zon),
),
]
}
pub fn formats() -> &'static [Format] {
static FORMATS: OnceLock<Vec<Format>> = OnceLock::new();
FORMATS.get_or_init(|| {
let mut formats: Vec<Format> = packages()
.into_iter()
.filter_map(|(described, reader)| {
let Described {
descriptor,
transduce,
} = described?;
let part = Part::from_descriptor(&descriptor)?;
let transducer = Part::transducer(&descriptor, transduce.as_ref()).flatten();
Some(Format {
part,
reader,
transducer,
compiled: OnceLock::new(),
})
})
.collect();
formats.sort_by(|a, b| a.part.id.cmp(&b.part.id));
formats
})
}
pub fn format(id: &str) -> Option<&'static Format> {
formats().iter().find(|f| f.id() == id)
}
pub fn names() -> String {
names_of(formats().iter().map(Format::id))
}
pub fn parser_names() -> String {
names_of(formats().iter().filter(|f| f.parses()).map(Format::id))
}
fn names_of<'a>(ids: impl Iterator<Item = &'a str>) -> String {
let ids: Vec<&str> = ids.collect();
match ids.split_last() {
Some((last, [])) => last.to_string(),
Some((last, rest)) => format!("{} or {last}", rest.join(", ")),
None => String::new(),
}
}
pub struct Request<'a> {
pub from: &'a Format,
pub to: &'a Format,
pub path: Option<Vec<Segment>>,
pub options: Options,
pub program: Option<(&'a str, &'a str)>,
pub whole: bool,
pub limits: Limits,
}
pub struct Compiled {
pub composition: Composition,
pub program: Program,
parsed: Option<(Composition, Program)>,
}
pub fn compile(request: &Request<'_>) -> Result<Compiled, Fail> {
let routers = Arc::new(tabnas_transduce::routers());
let renderers = renderers();
let transducer = match (&request.path, request.whole) {
(None, false) => request.from.transducer(),
_ => None,
};
let (composition, program, parsed) = match request.program {
Some((file, text)) => {
let output =
tabnas_alchemy::compile(text, file, routers.clone(), renderers.clone())?.output();
if output == Output::Text {
return Err(Fail::new(
Code::DslTypeError,
format!(
"bad_output: {file}'s export writes its own text, and translate takes a \
program whose export answers JSON events or a table, which a format's \
render then writes"
),
));
}
let composition =
compose_program(output, &request.to.part, &request.options, "translate")?;
let program = composition.compile(
Some(Source::new(file, text)),
routers.clone(),
renderers.clone(),
)?;
let parsed = match transducer {
Some(alc) => {
let composition = compose_program_parsed(
output,
alc,
&request.to.part,
&request.options,
"translate",
)?;
let program =
composition.compile(Some(Source::new(file, text)), routers, renderers)?;
Some((composition, program))
}
None => None,
};
(composition, program, parsed)
}
None => {
let source = match request.path {
Some(_) => None,
None => Some(&request.from.part),
};
let composition = compose(source, &request.to.part, &request.options, "translate")?;
let program = composition.compile(None, routers.clone(), renderers.clone())?;
let parsed = match transducer {
Some(alc) => {
let composition = compose_parsed(
&request.from.part,
alc,
&request.to.part,
&request.options,
"translate",
)?;
let program = composition.compile(None, routers, renderers)?;
Some((composition, program))
}
None => None,
};
(composition, program, parsed)
}
};
Ok(Compiled {
composition,
program,
parsed,
})
}
fn unfollowed(fail: &Fail) -> bool {
matches!(
fail.code,
Code::StreamabilityUnknown | Code::DuplicateMember
)
}
const WHOLE: &str = "; --whole reads the document whole";
pub enum Document<'a> {
Text(&'a str),
File(&'a Path),
Reader(Box<dyn Read + Send>),
}
#[cfg(test)]
thread_local! {
static READ_THROUGH_A_READER: std::cell::RefCell<Vec<std::path::PathBuf>> =
const { std::cell::RefCell::new(Vec::new()) };
}
pub fn run(
request: &Request<'_>,
input: &str,
out: Box<dyn Write + Send>,
metrics: Arc<Metrics>,
) -> Result<(), Fail> {
run_compiled(request, &compile(request)?, input, out, metrics)
}
pub fn run_compiled(
request: &Request<'_>,
compiled: &Compiled,
input: &str,
out: Box<dyn Write + Send>,
metrics: Arc<Metrics>,
) -> Result<(), Fail> {
run_document(request, compiled, Document::Text(input), out, metrics)
}
pub fn run_document(
request: &Request<'_>,
compiled: &Compiled,
document: Document<'_>,
out: Box<dyn Write + Send>,
metrics: Arc<Metrics>,
) -> Result<(), Fail> {
run_once(request, compiled, document, out, metrics.clone()).map_err(|fail| {
if Metrics::get(&metrics.output_bytes) > 0 && !fail.committed_output {
fail.committed()
} else {
fail
}
})
}
fn run_once(
request: &Request<'_>,
compiled: &Compiled,
document: Document<'_>,
out: Box<dyn Write + Send>,
metrics: Arc<Metrics>,
) -> Result<(), Fail> {
let Compiled {
composition,
program,
parsed,
} = compiled;
if let Some((_, part)) = parsed {
let sink = part.parser_sink(out, None, &request.limits, metrics.clone())?;
return run_passes(request, document, sink, metrics);
}
if let Some(path) = &request.path {
return run_path(request, program, path, document, out, metrics);
}
let text = text_of(document)?;
let sink = program.sink(out, None, &request.limits, metrics.clone())?;
let sink: Box<dyn Sink + Send> = match composition.front {
Front::Tree => Box::new(TreeContract::new(sink)),
_ => sink,
};
source(request.from, &text, &request.limits, metrics, sink).0?;
Ok(())
}
fn run_path(
request: &Request<'_>,
program: &Program,
path: &[Segment],
document: Document<'_>,
out: Box<dyn Write + Send>,
metrics: Arc<Metrics>,
) -> Result<(), Fail> {
let inner = program.sink(out, None, &request.limits, metrics.clone())?;
let scope: Box<dyn Sink + Send> = Box::new(TreeContract::new(AtPath::new(path, inner)));
let part = match request.whole {
true => None,
false => request.from.transducer_program()?,
};
match part {
Some(part) => {
let head = part.parser_sink_into(scope, &request.limits, metrics.clone())?;
run_passes(request, document, head, metrics)
}
None => {
let text = text_of(document)?;
source(request.from, &text, &request.limits, metrics, scope).0?;
Ok(())
}
}
}
fn run_passes(
request: &Request<'_>,
document: Document<'_>,
head: Box<dyn tabnas_transduce::ParserSink + Send>,
metrics: Arc<Metrics>,
) -> Result<(), Fail> {
let passes = match document {
Document::Text(text) => request.from.passes(text),
Document::File(path) => {
#[cfg(test)]
READ_THROUGH_A_READER.with(|read| read.borrow_mut().push(path.into()));
std::fs::File::open(path)
.map_err(cannot_read)
.and_then(|file| request.from.passes_from(Box::new(file)))
}
Document::Reader(reader) => request.from.passes_from(reader),
}?;
request
.from
.pruned(passes)
.limits(request.limits.clone())
.metrics(metrics)
.run_boxed(head)
.0
.map(|_| ())
.map_err(|mut fail| {
if unfollowed(&fail) && request.program.is_none() {
fail.message.push_str(WHOLE);
}
fail
})
}
fn text_of(document: Document<'_>) -> Result<std::borrow::Cow<'_, str>, Fail> {
match document {
Document::Text(text) => Ok(std::borrow::Cow::Borrowed(text)),
Document::File(path) => read_file(path).map(std::borrow::Cow::Owned),
Document::Reader(mut reader) => {
let mut whole = String::new();
reader.read_to_string(&mut whole).map_err(cannot_read)?;
Ok(std::borrow::Cow::Owned(whole))
}
}
}
struct Around {
array: bool,
next: usize,
named: bool,
on_path: bool,
}
struct AtPath {
path: Vec<Segment>,
inner: Box<dyn Sink + Send>,
around: Vec<Around>,
depth: usize,
found: bool,
}
impl AtPath {
fn new(path: &[Segment], inner: Box<dyn Sink + Send>) -> AtPath {
AtPath {
path: path.to_vec(),
inner,
around: Vec::new(),
depth: 0,
found: false,
}
}
fn on_path(&mut self) -> bool {
let level = self.around.len();
let Some(top) = self.around.last_mut() else {
return true;
};
let index = top.next;
if top.array {
top.next += 1;
}
if !top.on_path || level > self.path.len() {
return false;
}
match top.array {
true => matches!(self.path[level - 1], Segment::Index(i) if i == index),
false => top.named,
}
}
}
impl Sink for AtPath {
fn event(&mut self, ev: JsonEvent<'_>) -> Result<Flow, Fail> {
if self.depth > 0 {
match ev {
JsonEvent::ObjectStart | JsonEvent::ArrayStart => self.depth += 1,
JsonEvent::ObjectEnd | JsonEvent::ArrayEnd => self.depth -= 1,
_ => {}
}
if self.depth == 0 {
self.found = true;
}
return self.inner.event(ev);
}
match ev {
JsonEvent::Key(key) => {
let level = self.around.len();
let path = &self.path;
if let Some(top) = self.around.last_mut() {
top.named = top.on_path
&& level <= path.len()
&& matches!(&path[level - 1], Segment::Key(k) if &**k == key);
}
Ok(Flow::Continue)
}
JsonEvent::ObjectEnd | JsonEvent::ArrayEnd => {
self.around.pop();
Ok(Flow::Continue)
}
JsonEvent::End if !self.found => Err(Fail::input(format!(
"the path {} names nothing in the document",
path_text(&self.path)
))),
JsonEvent::End => self.inner.event(ev),
_ => {
let on_path = self.on_path();
let container = matches!(ev, JsonEvent::ObjectStart | JsonEvent::ArrayStart);
if on_path && self.around.len() == self.path.len() {
match container {
true => self.depth = 1,
false => self.found = true,
}
return self.inner.event(ev);
}
if container {
self.around.push(Around {
array: matches!(ev, JsonEvent::ArrayStart),
next: 0,
named: false,
on_path,
});
}
Ok(Flow::Continue)
}
}
}
}
fn read_file(path: &Path) -> Result<String, Fail> {
std::fs::read_to_string(path).map_err(cannot_read)
}
fn cannot_read(error: std::io::Error) -> Fail {
Fail::input(format!("unreadable: {error}"))
}
pub fn unreadable(fail: &Fail) -> Option<&str> {
if fail.code != Code::InputInvalid {
return None;
}
let reason = fail.message.strip_prefix("unreadable: ")?;
Some(
reason
.strip_prefix("the source could not be read: ")
.unwrap_or(reason),
)
}
#[derive(Clone)]
struct Collect(Arc<std::sync::Mutex<DatumBuilder>>);
impl Collect {
fn new() -> Collect {
Collect(Arc::new(std::sync::Mutex::new(DatumBuilder::new(
usize::MAX,
"max_capture_bytes",
Duplicates::LastWins,
))))
}
fn builder(&self) -> std::sync::MutexGuard<'_, DatumBuilder> {
self.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
fn take(&self) -> Result<Datum, Fail> {
self.builder()
.take()
.ok_or_else(|| Fail::input("the document holds no value"))
}
}
impl Sink for Collect {
fn event(&mut self, ev: JsonEvent<'_>) -> Result<Flow, Fail> {
if !matches!(ev, JsonEvent::End) {
self.builder().event(ev)?;
}
Ok(Flow::Continue)
}
}
fn source<S: Sink + Send + 'static>(
format: &Format,
input: &str,
limits: &Limits,
metrics: Arc<Metrics>,
sink: S,
) -> (Result<Flow, Fail>, S) {
match format.reader {
Reader::Parser(parsing) => (parsing.events)(input)
.limits(limits.clone())
.metrics(metrics)
.run_owned(sink),
Reader::Checked(check, parsing) => match (check.text)(input) {
Err(refused) => (Err(refused), sink),
Ok(()) => (parsing.events)(input)
.limits(limits.clone())
.metrics(metrics)
.run_owned(sink),
},
Reader::Tree(read) | Reader::ParsedTree(_, read) => {
let mut guarded = Guarded::new(sink, limits, AbortFlag::new(), metrics);
let outcome = read(input).and_then(|tree| match walk_datum(&tree, &mut guarded)? {
Flow::Continue => guarded.event(JsonEvent::End),
Flow::Stop => Ok(Flow::Stop),
});
(outcome, guarded.into_inner())
}
}
}
fn read(format: &Format, input: &str, limits: &Limits) -> Result<Datum, Fail> {
let (outcome, collect) = source(format, input, limits, Metrics::new(), Collect::new());
outcome?;
collect.take()
}
fn read_through(
format: &Format,
part: &Program,
input: &str,
limits: &Limits,
) -> Result<Datum, Fail> {
let collect = Collect::new();
let metrics = Metrics::new();
let head = part.parser_sink_into(
Box::new(TreeContract::new(collect.clone())),
limits,
metrics.clone(),
)?;
format
.passes(input)?
.limits(limits.clone())
.metrics(metrics)
.run_boxed(head)
.0?;
collect.take()
}
pub fn parse_path(text: &str, limits: &Limits) -> Result<Vec<Segment>, Fail> {
let json = format("json").ok_or_else(|| Fail::input("no JSON grammar to read the path"))?;
let refuse = || {
Fail::input(format!(
"--path takes a JSON array of keys and indexes, such as [\"people\",0], not {text}"
))
};
let value = json.read(text, limits).map_err(|_| refuse())?;
let Some(items) = value.as_array() else {
return Err(refuse());
};
items
.iter()
.map(|item| match item {
Datum::String(key) => Ok(Segment::Key(key.clone())),
Datum::Number { value, .. }
if value.fract() == 0.0 && *value >= 0.0 && *value <= usize::MAX as f64 =>
{
Ok(Segment::Index(*value as usize))
}
_ => Err(refuse()),
})
.collect()
}
fn path_text(path: &[Segment]) -> String {
let items: Vec<Datum> = path
.iter()
.map(|s| match s {
Segment::Key(k) => Datum::String(k.clone()),
Segment::Index(i) => Datum::Number {
value: *i as f64,
lexeme: Some(i.to_string().into()),
},
})
.collect();
Datum::Array(items).to_string()
}
pub fn formats_json() -> String {
let shape = |s: &Shape| {
Datum::String(
match s {
Shape::Tree => "tree",
Shape::Records => "records",
}
.into(),
)
};
let text = |s: &str| Datum::String(s.into());
let items: Vec<Datum> = formats()
.iter()
.map(|f| {
let p = &f.part;
let fields: [(&str, Datum); 11] = [
("id", text(&p.id)),
("reads", Datum::Array(p.reads.iter().map(shape).collect())),
("writes", shape(&p.writes)),
(
"root",
text(match p.root {
Root::Object => "object",
Root::Array => "array",
Root::Any => "any",
}),
),
("schema", p.schema.as_deref().map_or(Datum::Null, text)),
("whole", p.whole.as_deref().map_or(Datum::Null, text)),
(
"lift",
p.lift.as_ref().map_or(Datum::Null, |a| text(&a.entry)),
),
(
"embed",
p.embed.as_ref().map_or(Datum::Null, |a| text(&a.entry)),
),
(
"render",
text(match &p.render {
Render::Alc(a) => &a.entry,
Render::Json => "json",
Render::Csv => "csv",
}),
),
(
"transduce",
f.transducer
.as_ref()
.map_or(Datum::Null, |a| text(&a.entry)),
),
(
"loss",
Datum::Array(p.loss.iter().map(|l| text(l)).collect()),
),
];
Datum::Object(fields.into_iter().map(|(k, v)| (k.into(), v)).collect())
})
.collect();
Datum::Array(items).to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Clone, Default)]
struct Held(Arc<std::sync::Mutex<Vec<u8>>>);
impl Write for Held {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
const MARKING_TRANSDUCE: &str = "def json-transduce [input]\n as-events\n scan-emit\n []\n fn [s pass] (transition s [])\n fn [s] [object-start (key \"ran\") (scalar true) object-end]\n parser-events input\n";
fn plain_json() -> Format {
let json = format("json").expect("json is a format");
Format {
part: json.part.clone(),
reader: json.reader,
transducer: None,
compiled: OnceLock::new(),
}
}
fn transduced_json(text: &str) -> Format {
let json = format("json").expect("json is a format");
Format {
part: json.part.clone(),
reader: json.reader,
transducer: Some(Alc {
file: "tabnas-json/alchemy/transduce.alc".to_string(),
entry: "json-transduce".to_string(),
text: text.to_string(),
}),
compiled: OnceLock::new(),
}
}
fn translated(
from: &Format,
to: &str,
path: Option<&str>,
program: Option<(&str, &str)>,
input: &str,
) -> Result<String, Fail> {
translated_as(from, to, path, program, input, false)
}
fn translated_as(
from: &Format,
to: &str,
path: Option<&str>,
program: Option<(&str, &str)>,
input: &str,
whole: bool,
) -> Result<String, Fail> {
let limits = Limits::default();
let request = Request {
from,
to: format(to).expect("a format"),
path: path.map(|p| parse_path(p, &limits).expect("a path")),
options: Options::default(),
program,
whole,
limits,
};
let held = Held::default();
run(&request, input, Box::new(held.clone()), Metrics::new())?;
let bytes = held.0.lock().unwrap().clone();
Ok(String::from_utf8(bytes).expect("the output is UTF-8"))
}
#[test]
fn the_formats_read_through_a_transducer_part() {
let through: Vec<(&str, &str)> = formats()
.iter()
.filter_map(|f| f.transducer().map(|alc| (f.id(), alc.entry.as_str())))
.collect();
assert_eq!(
through,
[
("abnf", "abnf-transduce"),
("c", "c-transduce"),
("css", "css-transduce"),
("csv", "csv-transduce"),
("ebnf", "ebnf-transduce"),
("feed", "feed-transduce"),
("gbnf", "gbnf-transduce"),
("ini", "ini-transduce"),
("json", "json-transduce"),
("json5", "json5-transduce"),
("jsonc", "jsonc-transduce"),
("jsonic", "jsonic-transduce"),
("jsonl", "jsonl-transduce"),
("markdown", "markdown-transduce"),
("pgn", "pgn-transduce"),
("proto", "proto-transduce"),
("toml", "toml-transduce"),
("xml", "xml-transduce"),
("yaml", "yaml-transduce"),
("zon", "zon-transduce"),
]
);
}
#[test]
fn a_transducer_part_reads_the_format_and_the_walk_stands_in_where_it_is_asked() {
let plain = plain_json();
let through = format("json").expect("json is a format");
let marking = transduced_json(MARKING_TRANSDUCE);
assert!(plain.transducer().is_none());
assert_eq!(
through.transducer().map(|alc| alc.entry.as_str()),
Some("json-transduce"),
"the registry's json is read through its package's part"
);
assert!(through
.transducer()
.is_some_and(|alc| alc.text.contains("transduce-tree")));
let tree = r#"{"a":[1,2.50,"x",{"b":null}],"c":{},"d":[],"e":1e21,"f":true}"#;
let spelled = tree.replace("2.50", "2.5");
assert_eq!(
translated(through, "json", None, None, tree).unwrap(),
format!("{tree}\n"),
"the part keeps a number's lexeme"
);
assert_eq!(
translated(&plain, "json", None, None, tree).unwrap(),
format!("{spelled}\n"),
"the walk spells a number as the engine does"
);
let records = r#"[{"a":1,"b":"x"},{"a":2,"b":"y"}]"#;
let echo = Some(("echo.alc", "def export [input] (events input)\n"));
for (to, doc, program) in [
("json", spelled.as_str(), None),
("yaml", spelled.as_str(), None),
("csv", records, None),
("json", spelled.as_str(), echo),
("csv", records, echo),
] {
let expected =
translated(&plain, to, None, program, doc).expect("the plain route writes");
let got =
translated(through, to, None, program, doc).expect("the transducer's route writes");
assert_eq!(got, expected, "{to} from {doc} with {program:?}");
let marked = translated(&marking, to, None, program, doc);
assert_ne!(
marked.as_deref().ok(),
Some(expected.as_str()),
"{to} from {doc} with {program:?}: the part's route ran"
);
}
assert_eq!(
translated(&marking, "json", None, None, tree).unwrap(),
"{\"ran\":true}\n"
);
for (from, path, whole, want) in [
(through, "[\"a\",1]", false, "2.50\n".to_string()),
(
through,
"[\"a\"]",
false,
"[1,2.50,\"x\",{\"b\":null}]\n".to_string(),
),
(through, "[\"a\",3,\"b\"]", false, "null\n".to_string()),
(through, "[]", false, format!("{tree}\n")),
(&marking, "[\"ran\"]", false, "true\n".to_string()),
(through, "[\"a\",1]", true, "2.5\n".to_string()),
(&plain, "[\"a\",1]", false, "2.5\n".to_string()),
] {
assert_eq!(
translated_as(from, "json", Some(path), None, tree, whole).unwrap(),
want,
"{path} (whole {whole})"
);
}
let rows = format!("{{\"rows\":{records}}}");
assert_eq!(
translated(through, "csv", Some("[\"rows\"]"), echo, &rows).unwrap(),
translated(&plain, "csv", None, echo, records).unwrap()
);
for (from, path) in [
(through, "[\"a\",4]"),
(through, "[\"a\",\"0\"]"),
(through, "[\"c\",0]"),
(through, "[\"f\",\"g\"]"),
(&plain, "[\"z\"]"),
(&marking, "[\"a\"]"),
] {
let fail = translated(from, "json", Some(path), None, tree).unwrap_err();
assert_eq!(fail.code, Code::InputInvalid, "{path}: {fail:?}");
assert_eq!(
fail.message,
format!("the path {path} names nothing in the document")
);
assert!(!fail.committed_output, "{path}: {fail:?}");
}
let repeated = r#"{"a":1,"a":2}"#;
let streamed = translated(through, "json", None, None, repeated).unwrap_err();
assert_eq!(streamed.code, Code::DuplicateMember, "{streamed:?}");
assert!(streamed.message.ends_with(WHOLE), "{streamed:?}");
assert_eq!(
translated_as(through, "json", None, None, repeated, true).unwrap(),
translated(&plain, "json", None, None, repeated).unwrap()
);
assert_eq!(
translated_as(through, "json", None, None, repeated, true).unwrap(),
"{\"a\":2}\n"
);
let around = r#"{"x":{"a":1,"a":2},"y":3}"#;
for path in ["[\"x\"]", "[\"x\",\"a\"]", "[\"y\"]"] {
let streamed = translated(through, "json", Some(path), None, around).unwrap_err();
assert_eq!(streamed.code, Code::DuplicateMember, "{path}: {streamed:?}");
assert!(streamed.message.ends_with(WHOLE), "{path}: {streamed:?}");
}
for (path, want) in [("[\"x\"]", "{\"a\":2}\n"), ("[\"x\",\"a\"]", "2\n")] {
assert_eq!(
translated_as(through, "json", Some(path), None, around, true).unwrap(),
want,
"{path}"
);
}
let refused = translated(through, "json", None, None, "[1,").unwrap_err();
assert_eq!(refused.code, Code::InputInvalid);
}
#[test]
fn yaml_reads_a_sequence_entry_as_its_grammar_does() {
let yaml = format("yaml").expect("yaml is a format");
for (doc, want, repeats) in [
(
"a:\n b: 1\na:\n c: 2\n",
"{\"a\":{\"b\":1,\"c\":2}}\n",
true,
),
(
"- a:\n b: 1\n a:\n c: 2\n",
"[{\"a\":{\"b\":1,\"c\":2}}]\n",
true,
),
("- a:\n b: 1\n", "[{\"a\":null,\"b\":1}]\n", false),
("- a: 1\n b: 2\n", "[{\"a\":1,\"b\":2}]\n", false),
] {
if repeats {
let streamed = translated(yaml, "json", None, None, doc).unwrap_err();
assert_eq!(streamed.code, Code::DuplicateMember, "{doc:?}");
}
assert_eq!(
translated_as(yaml, "json", None, None, doc, repeats).unwrap(),
want,
"{doc:?}"
);
}
}
fn file_of(name: &str, bytes: &[u8]) -> std::path::PathBuf {
let file =
std::env::temp_dir().join(format!("dmog-translate-{}-{name}", std::process::id()));
std::fs::write(&file, bytes).expect("the file is written");
file
}
fn translated_file(
from: &Format,
to: &str,
path: Option<&str>,
file: &Path,
) -> Result<String, Fail> {
translated_file_as(from, to, path, file, false)
}
fn translated_file_as(
from: &Format,
to: &str,
path: Option<&str>,
file: &Path,
whole: bool,
) -> Result<String, Fail> {
let limits = Limits::default();
let request = Request {
from,
to: format(to).expect("a format"),
path: path.map(|p| parse_path(p, &limits).expect("a path")),
options: Options::default(),
program: None,
whole,
limits,
};
let held = Held::default();
run_document(
&request,
&compile(&request)?,
Document::File(file),
Box::new(held.clone()),
Metrics::new(),
)?;
let bytes = held.0.lock().unwrap().clone();
Ok(String::from_utf8(bytes).expect("the output is UTF-8"))
}
fn read_through_a_reader(file: &Path) -> bool {
READ_THROUGH_A_READER.with(|read| read.borrow().iter().any(|p| p == file))
}
#[test]
fn a_file_translates_as_its_text_does() {
let cases: &[(&str, &str, Option<&str>, &str)] = &[
(
"json",
"json",
None,
r#"{"a":[1,2.50,"x",{"b":null}],"c":{}}"#,
),
("json", "yaml", None, r#"[{"a":1},{"a":2}]"#),
("json", "csv", None, r#"[{"a":1,"b":"x"},{"a":2,"b":"y"}]"#),
("json", "json", None, r#"{"a":1,"a":2}"#),
("json", "json", None, "\u{feff}[1, 2]"),
("json", "json", None, "[1,"),
("json", "json", Some("[\"a\",1]"), r#"{"a":[1,2.50]}"#),
(
"jsonc",
"json",
None,
"// rows\n[{\"a\": 1, /* c */ \"b\": 2,}]",
),
("jsonl", "json", None, "{\"a\":1}\n{\"a\":2}\n"),
("csv", "json", None, "a,b\n1,\"x\"\n2,y\n"),
("json5", "json", None, "{a: 1, b: [2,],}"),
("json5", "json", None, "// only a comment"),
("yaml", "json", None, "a:\n b: 1\na:\n c: 2\n"),
("xml", "json", None, "<a><b>1</b></a>"),
("toml", "json", None, "a = 1\n[b]\nc = 2\n"),
];
for (index, (from, to, path, text)) in cases.iter().enumerate() {
let source = format(from).expect("a format");
let file = file_of(&format!("{index}.{from}"), text.as_bytes());
let whole = translated(source, to, *path, None, text);
let read = translated_file(source, to, *path, &file);
assert_eq!(
format!("{read:?}"),
format!("{whole:?}"),
"{from} {text:?} to {to} at {path:?}"
);
assert_eq!(
read_through_a_reader(&file),
source.transducer().is_some(),
"{from} {text:?} at {path:?}: the route"
);
let _ = std::fs::remove_file(&file);
}
}
#[test]
fn a_file_that_cannot_be_read_is_unreadable_on_every_route() {
let bad = file_of("bad.json", b"[1, \"\xff\"]");
let json = format("json").expect("json is a format");
let toml = format("toml").expect("toml is a format");
for (from, path) in [(json, None), (json, Some("[0]")), (toml, None)] {
let fail = translated_file(from, "json", path, &bad).unwrap_err();
assert_eq!(fail.code, Code::InputInvalid, "{fail:?}");
assert_eq!(
unreadable(&fail),
Some("stream did not contain valid UTF-8"),
"{} at {path:?}: {fail:?}",
from.id()
);
}
assert!(read_through_a_reader(&bad));
let _ = std::fs::remove_file(&bad);
let missing = std::env::temp_dir().join("dmog-translate-no-such-file.json");
let fail = translated_file(json, "json", None, &missing).unwrap_err();
let reason = std::fs::read_to_string(&missing).unwrap_err().to_string();
assert_eq!(unreadable(&fail), Some(reason.as_str()), "{fail:?}");
let fail = translated(json, "json", None, None, "[1,").unwrap_err();
assert_eq!(unreadable(&fail), None, "{fail:?}");
}
#[cfg(unix)]
#[test]
fn a_pipe_is_read_once() {
let json = format("json").expect("json is a format");
let repeated = r#"{"a":1,"a":2}"#;
for whole in [false, true] {
let fifo = std::env::temp_dir().join(format!(
"dmog-translate-{}-pipe-{whole}.json",
std::process::id()
));
let _ = std::fs::remove_file(&fifo);
let made = std::process::Command::new("mkfifo")
.arg(&fifo)
.status()
.expect("mkfifo runs");
assert!(made.success());
let writer = {
let fifo = fifo.clone();
std::thread::spawn(move || std::fs::write(&fifo, repeated))
};
let read = translated_file_as(json, "json", None, &fifo, whole);
writer.join().unwrap().expect("the pipe is written");
assert_eq!(
format!("{read:?}"),
format!(
"{:?}",
translated_as(json, "json", None, None, repeated, whole)
),
"whole: {whole}"
);
assert_eq!(read_through_a_reader(&fifo), !whole, "whole: {whole}");
let _ = std::fs::remove_file(&fifo);
}
}
fn elements(value: &tabnas::Value) -> usize {
match value {
tabnas::Value::Array(items) => items.len() + items.iter().map(elements).sum::<usize>(),
tabnas::Value::ListRef(list) => {
list.value.len() + list.value.iter().map(elements).sum::<usize>()
}
tabnas::Value::Object(map) => map.len() + map.values().map(elements).sum::<usize>(),
tabnas::Value::MapRef(map) => {
map.value.len() + map.value.values().map(elements).sum::<usize>()
}
_ => 0,
}
}
fn left(format: &Format, text: &str, prune: bool) -> usize {
let source = format.passes(text).expect("the format is parsed");
let source = if prune { format.pruned(source) } else { source };
let (outcome, _, value) = source.run_owned_with_value(Vec::new());
outcome.expect("the passes stream");
elements(&value.expect("a parse that completed returns a value"))
}
#[test]
fn a_listed_grammars_tree_is_emptied_behind_the_stream() {
let csv = |n: usize| {
let mut text = String::from("a,b\n");
for i in 0..n {
text.push_str(&format!("{i},x{i}\n"));
}
text
};
let jsonl = |n: usize| {
let mut text = String::new();
for i in 0..n {
text.push_str(&format!("{{\"a\":{i}}}\n"));
}
text
};
let json = |n: usize| {
let items: Vec<String> = (0..n).map(|i| format!("{{\"a\":{i}}}")).collect();
format!("[{}]", items.join(","))
};
let docs: [(&str, &dyn Fn(usize) -> String); 3] =
[("csv", &csv), ("jsonl", &jsonl), ("json", &json)];
for (id, doc) in docs {
let listed = format(id).expect("a format");
assert!(capability::prunable(id), "{id}");
assert_eq!(
left(listed, &doc(200), true),
left(listed, &doc(2000), true),
"{id}: pruned"
);
assert!(
left(listed, &doc(2000), false) >= left(listed, &doc(200), false) + 1800,
"{id}: not pruned"
);
}
let proto = format("proto").expect("proto is a format");
assert!(!capability::prunable("proto"));
let text =
"syntax = \"proto3\";\nmessage A { int32 a = 1; }\nmessage B { string b = 1; }\n";
for prune in [true, false] {
let source = proto.passes(text).expect("the format is parsed");
let source = if prune { proto.pruned(source) } else { source };
let (outcome, _, _) = source.run_owned_with_value(Vec::new());
outcome.expect("an unlisted grammar's passes stream, pruned or not");
}
}
#[test]
fn a_format_with_a_parser_gives_its_rule_passes() {
let parsed: Vec<&str> = formats()
.iter()
.filter(|f| f.parses())
.map(Format::id)
.collect();
assert_eq!(
parsed,
[
"abnf", "c", "css", "csv", "ebnf", "feed", "gbnf", "ini", "json", "json5", "jsonc",
"jsonic", "jsonl", "markdown", "pgn", "proto", "semver", "toml", "xml", "yaml",
"zon"
]
);
assert_eq!(
parser_names(),
"abnf, c, css, csv, ebnf, feed, gbnf, ini, json, json5, jsonc, jsonic, jsonl, markdown, \
pgn, proto, semver, toml, xml, yaml or zon"
);
let expr = format("expr").expect("expr is a format");
assert!(!expr.parses());
let refused = expr.passes("1+2").err().expect("a tree has no passes");
assert_eq!(refused.code, Code::InputInvalid);
assert!(
refused.message.starts_with("expr is read as a tree"),
"{refused}"
);
let json5 = format("json5").expect("json5 is a format");
let empty = json5
.passes("// only a comment")
.err()
.expect("the check refuses");
assert_eq!(empty.code, Code::InputInvalid);
let empty = json5
.passes_from(Box::new(&b"// only a comment"[..]))
.err()
.expect("the check refuses through a reader");
assert_eq!(empty.code, Code::InputInvalid);
let (outcome, passes) = json5
.passes("{a: 1}")
.expect("the check passes")
.run_owned(Vec::new());
outcome.expect("the passes stream");
assert!(!passes.is_empty());
}
}