# Use the Rust library

Add tabnas-dmog to a Rust project, translate a string or a stream, run a program, read a failure, and stop a run that is under way.

The `tabnas-dmog` crate is a library, `tabnas_dmog`, as well as the `dmog` command. A Rust program that depends on it can do everything the command does. The crate's tests run the examples on this page and check what each one returns. Every function and option is in [the library reference](https://dmog.tabnas.dev/reference/library.html).

## Add the crate

You need Rust 1.85 or later. Add the crate to your project:

```sh
cargo add tabnas-dmog
```

## Translate a document held in a string

`translate_str` compiles a translation and runs it over a string:

```rust
use tabnas_dmog::{translate_str, Fail, TranslateOptions};

fn main() -> Result<(), Fail> {
    let yaml = "name: Ada\nlanguages: [en, fr]\n";
    let json = translate_str(yaml, TranslateOptions::new("yaml", "json"))?;
    assert_eq!(json, "{\"name\":\"Ada\",\"languages\":[\"en\",\"fr\"]}\n");
    Ok(())
}
```

`TranslateOptions::new` takes the formats to read and write, by the ids `dmog formats` prints, and sets every other option to its default. The other fields are the command's options: `path`, `key`, `with`, and `whole` stand for `--path`, `--key`, `--with`, and `--whole`. `limits` holds the limits, `max_output_bytes` among them, which is `--max-output-bytes`.

To run one translation over many documents, compile it once with `Translation::new`:

```rust
use tabnas_dmog::{Fail, TranslateOptions, Translation};

/// Each CSV document as JSON, through one translation compiled once.
pub fn csv_documents_as_json(documents: &[&str]) -> Result<Vec<String>, Fail> {
    let translation = Translation::new(TranslateOptions::new("csv", "json"))?;
    documents
        .iter()
        .map(|document| translation.run_str(document))
        .collect()
}
```

`Translation::new` refuses a format that does not exist, a path that does not parse, and a program that does not check, before any document is read.

## Stream from a file

`translate` reads from a reader and writes to a writer as it reads:

```rust
use std::error::Error;
use std::fs::File;
use std::path::Path;

use tabnas_dmog::{translate, TranslateOptions};

/// Writes the YAML file `from` as TOML in `to`, as it reads it.
pub fn yaml_file_as_toml(from: &Path, to: &Path) -> Result<(), Box<dyn Error>> {
    let input = File::open(from)?;
    let output = File::create(to)?;
    translate(input, output, TranslateOptions::new("yaml", "toml"))?;
    Ok(())
}
```

The run takes place on a thread the library starts, so the reader and the writer move to it: each must be `Send` and `'static`, as a `File`, a `TcpStream`, and standard input and output are. `Translation::run` does the same with a translation compiled once.

A document that cannot be streamed, such as an object that repeats a key, fails with a message that ends by naming `--whole`. Set `whole` to `true` to read it whole, as [Translate a document that cannot be streamed](https://dmog.tabnas.dev/how-to/read-whole.html) does with the command.

## Run a program

`Program::new` takes an alchemy program as a `Source`, its name and its text, with the options of `dmog run`. `run` and `run_str` run it over a JSON document:

```rust
use std::error::Error;
use std::fs;
use std::path::Path;

use tabnas_dmog::{Program, ProgramOptions, Render, Source};

/// Runs the alchemy program in the file `program` over the JSON document in
/// the file `document`, and answers the table it makes as JSON records.
pub fn table_as_json(program: &Path, document: &Path) -> Result<String, Box<dyn Error>> {
    let source = Source::new(program.display().to_string(), fs::read_to_string(program)?);
    let options = ProgramOptions {
        render: Some(Render::Json),
        ..ProgramOptions::default()
    };
    let compiled = Program::new(source, options)?;
    Ok(compiled.run_str(&fs::read_to_string(document)?)?)
}
```

`render` stands for `--render`, and `grammar` for `--grammar`. `Program::new` refuses a program that does not check, and a render its export cannot take, before any document is read. `canon`, `format`, `check`, `explain`, and `explain_json` answer what the commands of those names print. To reshape a document while it is translated, give the program to a translation as its `with` option.

## Read a failure

Every failure is a `Fail`. Its `code` is the failure's stable name, and `committed_output` says whether output had been written before it:

```rust
use std::fs::File;
use std::path::Path;

use tabnas_dmog::{translate, Code, TranslateOptions};

/// Writes the JSON Lines file `from` as one JSON array in `to`. A failure
/// says what went wrong, and what `to` was left holding.
pub fn lines_as_array(from: &Path, to: &Path) -> Result<(), String> {
    let input = File::open(from).map_err(|error| error.to_string())?;
    let output = File::create(to).map_err(|error| error.to_string())?;
    translate(input, output, TranslateOptions::new("jsonl", "json")).map_err(|fail| {
        let what = match fail.code {
            Code::InputInvalid => "a line does not parse",
            Code::ResourceLimitExceeded => "a limit was reached",
            _ => "the translation failed",
        };
        let left = if fail.committed_output {
            "the records before the failure"
        } else {
            "nothing"
        };
        format!("{what} ({fail}), and {} holds {left}", to.display())
    })
}
```

`Fail` implements `std::error::Error`, and its `Display` writes the code, the message, and where the failure was found. `to_json` gives the object the command writes on standard error. Output written before a failure is a prefix of the answer, and ends with a whole record unless one record was longer than the 32 KiB the writer holds back. `run_str` and `translate_str` keep none of it. [Failures](https://dmog.tabnas.dev/reference/failures.html) lists every code.

## Stop a run

An `Abort` stops a run that is under way. Give one to `run_with_abort`, and call `abort` on it, or on a clone of it, from any thread. The run fails with `Code::Aborted`:

```rust
use std::io::{Read, Write};
use std::thread;
use std::time::Duration;

use tabnas_dmog::{Abort, Fail, TranslateOptions, Translation};

/// Writes the JSON `input` gives as YAML to `output`, and stops the run
/// once `budget` has passed.
pub fn json_as_yaml_within<R, W>(input: R, output: W, budget: Duration) -> Result<(), Fail>
where
    R: Read + Send + 'static,
    W: Write + Send + 'static,
{
    let translation = Translation::new(TranslateOptions::new("json", "yaml"))?;
    let abort = Abort::new();
    let timer = abort.clone();
    thread::spawn(move || {
        thread::sleep(budget);
        timer.abort();
    });
    translation.run_with_abort(input, output, &abort)
}
```

The run checks its `Abort` between the steps of its parse and as its program's functions run, and a run given one that has already been aborted fails before it reads anything. A read that blocks, such as one from a network connection that stops sending, holds the run until the read returns, so give such a reader a timeout of its own, as `TcpStream::set_read_timeout` does.

## Share a translation between threads

`Translation`, `Program`, and `Abort` are `Send` and `Sync`, so one translation compiled once can serve runs on many threads at once. Every compile and every run takes place on a thread of its own with a 64 MiB stack, which the language's bounds on a program's nesting need, so the library can be called from any thread, whatever its stack size.
