Rust
Rust is the reference implementation of Iris. The gecode-iris crate
re-exports the public reader API from gecode-iris-core; import it as gecode_iris.
It returns named, typed entries, including arrays whose rows have different lengths.
Add the dependency
Section titled “Add the dependency”Use Rust 1.88 or newer. Add this to your application’s Cargo.toml, or run
cargo add gecode-iris:
[dependencies]gecode-iris = "0.1"Package versions and language versions are separate; the current Rust packages are 0.1.0 and implement Iris 0.1.
Parse once, read input, borrow a row
Section titled “Parse once, read input, borrow a row”Put this in your application’s src/main.rs. It follows the umbrella
crate’s doc-tested example, wrapped in main.
fn main() -> Result<(), Box<dyn std::error::Error>> { use gecode_iris::{Params, Spec};
let spec = Spec::parse(b"n:int row[n]:int", "example.iris")?; let data = spec.read(b"3 10 20 30", "input.txt", &Params::new())?; assert_eq!(data.int("n")?, 3); assert_eq!(data.ints("row", &[])?, &[10, 20, 30]); Ok::<(), Box<dyn std::error::Error>>(())}Spec::parse validates the reader spec. The declaration reads n, then a row
of n integers. Spec::read reads input bytes using caller parameters; an empty
Params supplies none. Origin names such as example.iris and input.txt
appear in diagnostics.
Data::int returns a scalar. Data::ints borrows an integer row without copying
it. The empty index path selects the whole one-dimensional row here; for a column
of rows, the path selects a row. The returned Data owns its entries and does
not borrow the original input bytes, so the same Spec can read another input.
To run the original example from the Iris checkout, use its rust/ directory:
cargo test --locked -p gecode-iris --docFiles, parameters, and output
Section titled “Files, parameters, and output”Spec::read_path reads a file with caller parameters. Spec::catalog and
catalog_path traverse a multi-instance file and return catalog data.
The instance parameter selects an instance during a read by ordinal or name;
see parameters and instances.
Data::entries visits entries in definition order. Data::value selects a
borrowed value by name and index path. to_json and to_dzn return buffered
output; write_dzn writes to an io::Write destination. A stream error can leave
partial bytes in that destination. The data model
and dzn appendix define the representations.
Handle failures
Section titled “Handle failures”Parsing and reading return Failure. Failure::Language contains an error
with a stable language code, source locations and,
when applicable, a record path. Work-budget exhaustion is a language failure
(E-BUDGET). Failure::Host covers host
failures such as file acquisition or cancellation. Failure::Unsupported
identifies an implementation feature that has not been implemented.
After a successful read, typed lookup returns AccessError for an unknown name,
invalid index path or incompatible requested type. These are host API usage
errors. Failure, HostError and AccessError are non-exhaustive; matching their
variants requires a fallback arm.
For more detail, read the
umbrella crate source
and core API guide.
Publication on docs.rs is planned; until then, cargo doc in the workspace
builds the API documentation locally.
Build a reader spec in code
Section titled “Build a reader spec in code”gecode_iris::build writes a reader spec from Rust calls. Every statement that
defines an entry returns a typed handle, so a misspelled entry or a wrong value
type fails when the program compiles, not when data is read. A builder adds no
features of its own: build() prints Iris text and parses it with Spec::parse,
so the language’s checks decide what is valid, and source() returns the text.
The examples below are in
rust/gecode-iris/examples,
one builder for each format in the format library. A test reads every
case of each format through its builder and compares the data with the case’s
expected results, then runs each program and compares its output with the
output shown here. The programs read files from the format library, so run them
from the root of an Iris checkout, as in
cargo run --manifest-path rust/Cargo.toml --example jobshop.
The job shop builder
Section titled “The job shop builder”This builder writes the job shop reader spec. main reads
an instance selected by name, then a file whose check fails.
use gecode_iris::build::{ BuildError, D0, D2, Field, Int, Maybe, SpecBuilder, Str, distinct, gecode, lit, pattern, sum, sum_over, word,};use gecode_iris::{Params, Spec};
/// A job shop reader and the entries a scheduler needs.pub struct Jobshop { pub spec: Spec, pub name: Field<Str, D0, Maybe>, pub n_jobs: Field<Int>, pub n_machines: Field<Int>, pub machine: Field<Int, D2>, pub duration: Field<Int, D2>,}
/// Reads OR-Library and JSPLIB files: a header line with the numbers of jobs/// and machines, then one line per job of machine and duration pairs.pub fn jobshop() -> Result<Jobshop, BuildError> { let mut b = SpecBuilder::new("jobshop"); b.comment(["#", "+++"]); let (name, n_jobs, n_machines, machine, duration) = b.instances(|i| { let name = i.optional_capture("name", word()); let n_jobs = i.capture("n_jobs", 1..); let n_machines = i.capture("n_machines", 1..); let (job, machine, duration) = i.sections().skip_other().body(|s| { s.arm(pattern!("instance {name}")).optional(); s.arm(pattern!("{n_jobs} {n_machines}")).last().body(|a| { a.check(n_jobs.le((gecode::INT_MAX - 2) / 2 / n_machines)) .message("there are too many jobs and machines"); a.repeat(n_jobs, |job| { job.as_name("jobs"); // error messages name the records let (machine, duration) = job.repeat(n_machines, |step| { let machine = step.read("machine", lit(0)..n_machines.ex()); let duration = step.read("duration", 0..); (machine, duration) }); (job.record(), machine, duration) }) }) }); i.check(distinct(job.get(machine))) .message("a job uses a machine twice; each job must use every machine once"); i.check(sum_over(job, |j| sum(j.get(duration))).le(gecode::INT_MAX)) .message("the total duration is too large"); (name, n_jobs, n_machines, machine, duration) }); Ok(Jobshop { spec: b.build()?, name, n_jobs, n_machines, machine, duration, })}
fn main() -> Result<(), Box<dyn std::error::Error>> { let jobshop = jobshop()?;
let mut params = Params::new(); params.set("instance", "handmade-or"); let data = jobshop .spec .read_path("formats/jobshop/cases/or-library/input.txt", ¶ms)?; let name: Option<&str> = data.get(jobshop.name); let jobs: i64 = data.get(jobshop.n_jobs); let machines: i64 = data.get(jobshop.n_machines); println!( "{}: {jobs} jobs on {machines} machines", name.unwrap_or("unnamed") ); let steps = data.get(jobshop.machine).rows(); for (job, (machine, duration)) in steps.zip(data.get(jobshop.duration).rows()).enumerate() { println!("job {job}: machines {machine:?}, durations {duration:?}"); }
params.set("instance", "handmade-invalid"); let path = "formats/jobshop/cases/duplicate-machine/input.txt"; if let Err(error) = jobshop.spec.read_path(path, ¶ms) { println!("\n{error}"); } Ok(())}handmade-or: 3 jobs on 3 machines
job 0: machines [0, 1, 2], durations [2, 3, 1]
job 1: machines [1, 2, 0], durations [1, 4, 2]
job 2: machines [2, 0, 1], durations [3, 1, 2]
formats/jobshop/cases/duplicate-machine/input.txt:3:1: check failed for record 1 of 'jobs': a job uses a machine twice; each job must use every machine once
3 | 0 2 0 3 2 1
| ^
while reading: instance [1]
spec: builder.iris:17
call site: gecode-iris/examples/jobshop.rs:42:11
Blocks are closures that take the open scope and return the handles defined in
them. A capture is declared before the pattern that binds it, so pattern! can
interpolate it the way format! interpolates a variable. job.record() is the
handle of a repeat’s records: job.get(machine) prints job.machine, and
sum_over(job, ...) prints a comprehension over the jobs. The builder names
records itself; as_name("jobs") gives the records a name for error messages.
Rust’s a..b excludes b, so it prints as Iris a..<b, and a..=b prints as
Iris a..b. A handle or a host constant beside another bound needs .ex(), as
in lit(0)..n_machines.ex().
Typed data
Section titled “Typed data”data.get(handle) returns the Rust type of the entry’s value type and depth: an
i64 for n_jobs, an Option<&str> for the name, which only some files
give, and rows of &[i64] for machine and duration, which have one value
per step of each job. These are borrowed views of the data, without copies, and a lookup through
a handle cannot fail on a name or a type.
Errors name your code
Section titled “Errors name your code”Every statement records the line of the call that wrote it. When a check fails
while reading, the error shows the input line, the line of the built text
(spec: builder.iris:17) and a call site: line that names the distinct
check in jobshop.rs. A BuildError from build() has the same call site
line. A statement in a helper function records the line in the helper, unless
the helper has #[track_caller], as clue_lines below does.
A helper used twice
Section titled “A helper used twice”A function that takes a scope and returns handles is a reusable piece of a reader spec. The nonogram builder reads the clues of the rows and the columns with one helper, and builds two pairs of checks with two expression helpers.
use gecode_iris::build::{ BuildError, D2, Expr, Field, Int, Record, Scope, SpecBuilder, count, eol, min, pattern, size, sum, ty,};use gecode_iris::{Params, Spec};
/// A nonogram reader: the board size and the clues of each row and column.pub struct Nonogram { pub spec: Spec, pub width: Field<Int>, pub height: Field<Int>, pub row: Field<Int, D2>, pub col: Field<Int, D2>,}
/// The clue lines of one side of the board.struct Clues { lines: Record, clues: Field<Int, D2>,}
/// Reads `count` lines of comma-separated clues into the entry `name`.#[track_caller]fn clue_lines(s: &mut Scope, count: Field<Int>, name: &str) -> Clues { s.repeat(count, |line| Clues { lines: line.record(), clues: line.list(name, ty(0..).until(eol())), })}
/// A 0 clue says the line is empty, so it must stand alone.fn zero_stands_alone(clues: Field<Int, D2>) -> Expr<Int> { count(clues).le(1) | min(clues).gt(0)}
/// The clues and one gap between each pair of them fit into `length`.fn clues_fit(clues: Field<Int, D2>, length: Field<Int>) -> Expr<Int> { (sum(clues) + count(clues) - 1).le(length)}
pub fn nonogram() -> Result<Nonogram, BuildError> { let mut b = SpecBuilder::new("nonogram"); b.separators(","); let width = b.capture("width", 1..); let height = b.capture("height", 1..); let (rows, cols) = b.sections().skip_other().body(|s| { s.arm(pattern!("width {width}")); s.arm(pattern!("height {height}")); let rows = s.arm("rows").body(|a| clue_lines(a, height, "row")); let cols = s.arm("columns").body(|a| clue_lines(a, width, "col")); (rows, cols) }); let (row, col) = (rows.clues, cols.clues);
b.check(height.le(1_000_000 / width)) .message("the board must have at most a million fields"); b.check(size(rows.lines).eq(height) & size(cols.lines).eq(width)) .message("the numbers of rows and columns differ from the board size"); b.check(zero_stands_alone(row)) .message("a 0 must be the only clue of its row"); b.check(zero_stands_alone(col)) .message("a 0 must be the only clue of its column"); b.check(clues_fit(row, width)) .message("the clues of a row do not fit into the width of the board"); b.check(clues_fit(col, height)) .message("the clues of a column do not fit into the height of the board"); Ok(Nonogram { spec: b.build()?, width, height, row, col, })}
fn main() -> Result<(), Box<dyn std::error::Error>> { let nonogram = nonogram()?; let path = "formats/nonogram/cases/five-by-five/input.txt"; let data = nonogram.spec.read_path(path, &Params::new())?; let (width, height): (i64, i64) = (data.get(nonogram.width), data.get(nonogram.height)); println!("{width}x{height} board"); println!( "rows: {:?}", data.get(nonogram.row).rows().collect::<Vec<_>>() ); println!( "columns: {:?}", data.get(nonogram.col).rows().collect::<Vec<_>>() ); Ok(())}5x5 board
rows: [[1, 1], [1, 1], [1], [1, 1], [1, 1]]
columns: [[1, 1], [1, 1], [1], [1, 1], [1, 1]]
A builder rejects a second definition of a name, so a helper called twice by
mistake fails build() instead of quietly replacing an entry. That is why
clue_lines takes the entry name from its caller. The TSPLIB builder below
uses the same idea for its two coordinate sections.
The other formats
Section titled “The other formats”use gecode_iris::build::{BuildError, D2, Field, Int, SpecBuilder, gecode, lit, pattern, ty};use gecode_iris::{Params, Spec};
/// A DIMACS CNF reader: the number of variables and one row of literals per/// clause.pub struct DimacsCnf { pub spec: Spec, pub vars: Field<Int>, pub clause: Field<Int, D2>,}
pub fn dimacs_cnf() -> Result<DimacsCnf, BuildError> { let mut b = SpecBuilder::new("dimacs-cnf"); b.comment("c"); b.stop("%"); // SATLIB files end with "%" and "0" let vars = b.capture("vars", lit(0)..=gecode::INT_MAX.ex()); let clauses = b.capture("clauses", 0..); b.line(pattern!("p cnf {vars} {clauses}")); let clause = b.repeat(clauses, |c| { // The terminating 0 is not stored. c.list("clause", ty(-vars..=vars.ex()).until(0)) }); Ok(DimacsCnf { spec: b.build()?, vars, clause, })}
fn main() -> Result<(), Box<dyn std::error::Error>> { let cnf = dimacs_cnf()?; let path = "formats/dimacs-cnf/cases/three-variables/input.txt"; let data = cnf.spec.read_path(path, &Params::new())?; let vars: i64 = data.get(cnf.vars); println!("{vars} variables"); for clause in data.get(cnf.clause).rows() { println!("{clause:?}"); } Ok(())}3 variables
[1, -2]
[2, 3, -1]
[-3]
use gecode_iris::build::{BuildError, D2, Field, Int, SpecBuilder, alphabet, max, pattern};use gecode_iris::{Params, Spec};
/// A Sudoku reader: the grid size, the box size, and the cells, with 0 for a/// blank.pub struct Sudoku { pub spec: Spec, pub n: Field<Int>, pub box_width: Field<Int>, pub box_height: Field<Int>, pub cells: Field<Int, D2>,}
/// Cell values from 1 to 36, so `1` reads as 1 and `0` as 36.const SYMBOLS: &str = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0";
pub fn sudoku() -> Result<Sudoku, BuildError> { let mut b = SpecBuilder::new("sudoku"); let (n, box_width, box_height, cells) = b.instances(|i| { let n = i.capture("n", 1..); let box_width = i.capture("box_width", 1..); let box_height = i.capture("box_height", 1..); i.line(pattern!("# size={n} box={box_width}x{box_height}")); let cells = i.read("cells", alphabet(SYMBOLS).blank(".").dim(n).dim(n)); i.check((box_width * box_height).eq(n)) .message("boxes must tile the grid"); i.check(max(cells).le(n)) .message("a value is larger than the size of the grid"); (n, box_width, box_height, cells) }); Ok(Sudoku { spec: b.build()?, n, box_width, box_height, cells, })}
fn main() -> Result<(), Box<dyn std::error::Error>> { let sudoku = sudoku()?; let path = "formats/sudoku/cases/four-by-four/input.txt"; let data = sudoku.spec.read_path(path, &Params::new())?; let n: i64 = data.get(sudoku.n); let (width, height): (i64, i64) = (data.get(sudoku.box_width), data.get(sudoku.box_height)); println!("{n}x{n} grid with {width}x{height} boxes"); for row in data.get(sudoku.cells).rows() { println!("{row:?}"); } Ok(())}4x4 grid with 2x2 boxes
[1, 0, 0, 4]
[0, 4, 1, 0]
[0, 1, 4, 0]
[4, 0, 0, 1]
define_type gives a named type, used here for both ends of a time window:
use gecode_iris::build::{BuildError, D1, D2, Field, Int, SpecBuilder, gecode, lit, ty};use gecode_iris::{Params, Spec};
/// A reader for the travelling salesman problem with time windows: a distance/// matrix and a time window for each node, with the depot as node 0.pub struct Tsptw { pub spec: Spec, pub n: Field<Int>, pub dist: Field<Int, D2>, pub ready: Field<Int, D1>, pub due: Field<Int, D1>,}
pub fn tsptw() -> Result<Tsptw, BuildError> { let mut b = SpecBuilder::new("tsptw"); b.comment("#"); let n = b.read("n", 2..=1000); let dist = b.read("dist", ty(lit(0)..=gecode::INT_MAX / 2 / n).dim(n).dim(n));
let time = b.define_type("time", lit(0)..=gecode::INT_MAX / 2); let (node, ready, due) = b.repeat(n, |node| { node.as_name("nodes"); ( node.record(), node.read("ready", time), node.read("due", time), ) });
b.check(node.get(ready).le(node.get(due))) .message("the time window of a node is invalid"); b.check(node.at(0).get(ready).eq(0)) .message("the depot (node 0) must open at time 0"); Ok(Tsptw { spec: b.build()?, n, dist, ready, due, })}
fn main() -> Result<(), Box<dyn std::error::Error>> { let tsptw = tsptw()?; let path = "formats/tsptw/cases/three-nodes/input.txt"; let data = tsptw.spec.read_path(path, &Params::new())?; let n: i64 = data.get(tsptw.n); println!("{n} nodes"); let windows = data.get(tsptw.ready).iter().zip(data.get(tsptw.due)); for (node, (distances, (ready, due))) in data.get(tsptw.dist).rows().zip(windows).enumerate() { println!("node {node}: open {ready}..{due}, distances {distances:?}"); } Ok(())}3 nodes
node 0: open 0..20, distances [0, 2, 4]
node 1: open 2..8, distances [3, 0, 2]
node 2: open 5..12, distances [4, 3, 0]
A TSPLIB file gives either a distance matrix or coordinates. s.set gives an
optional entry a default while keeping its handle’s type, and if_ and else_
take the checks that apply to each kind of file:
use gecode_iris::build::{ Arms, BuildError, D0, D1, D2, Field, Float, Int, Maybe, Record, SpecBuilder, Str, defined, float, gecode, int, lit, pattern, rest, size, ty, word,};use gecode_iris::{Params, Spec};
/// A TSPLIB reader. A file gives either an explicit distance matrix or node/// coordinates, from which the distances follow.pub struct Tsplib { pub spec: Spec, pub name: Field<Str, D0, Maybe>, pub n: Field<Int>, pub edge_weight_type: Field<Str, D0, Maybe>, pub weight: Field<Int, D2, Maybe>, pub x: Field<Float, D1, Maybe>, pub y: Field<Float, D1, Maybe>,}
/// The entries of one section of numbered coordinates.struct Coordinates { nodes: Record, x: Field<Float, D1, Maybe>, y: Field<Float, D1, Maybe>,}
/// Adds the optional section `title` of `n` lines `node x y`, with the/// entries named `{prefix}node`, `{prefix}x` and `{prefix}y`.#[track_caller]fn coordinate_section(arms: &mut Arms, title: &str, n: Field<Int>, prefix: &str) -> Coordinates { arms.arm(title).optional().body(|a| { a.repeat(n, |line| { line.read(format!("{prefix}node"), int()); Coordinates { nodes: line.record(), x: line.read(format!("{prefix}x"), float()), y: line.read(format!("{prefix}y"), float()), } }) })}
pub fn tsplib() -> Result<Tsplib, BuildError> { let mut b = SpecBuilder::new("tsplib"); b.comment("COMMENT"); let name = b.optional_capture("name", rest()); let problem_type = b.optional_capture("type", word()); let n = b.capture("n", 2..=46340); let edge_weight_type = b.optional_capture("edge_weight_type", word()); let edge_weight_format = b.optional_capture("edge_weight_format", word()); let node_coord_type = b.optional_capture("node_coord_type", word()); let display_data_type = b.optional_capture("display_data_type", word()); let (nodes, x, y, weight) = b.sections().until("EOF").body(|s| { s.arm(pattern!("NAME : {name}")).optional(); s.arm(pattern!("TYPE : {problem_type}")).optional(); s.arm(pattern!("DIMENSION : {n}")); s.arm(pattern!("EDGE_WEIGHT_TYPE : {edge_weight_type}")) .optional(); s.arm(pattern!("EDGE_WEIGHT_FORMAT : {edge_weight_format}")) .optional(); s.arm(pattern!("NODE_COORD_TYPE : {node_coord_type}")) .optional(); s.arm(pattern!("DISPLAY_DATA_TYPE : {display_data_type}")) .optional(); let Coordinates { nodes, x, y } = coordinate_section(s, "NODE_COORD_SECTION", n, ""); let weight = s.arm("EDGE_WEIGHT_SECTION").optional().body(|a| { a.if_(!defined(edge_weight_format), |t| { t.set(edge_weight_format, lit("FULL_MATRIX")); }); let bound = gecode::INT_MAX / n; a.read( "weight", ty(lit(0)..=bound).dim(n).dim(n).layout(edge_weight_format), ) }); coordinate_section(s, "DISPLAY_DATA_SECTION", n, "display_"); (nodes, x, y, weight) }); b.if_(!defined(edge_weight_type), |t| { t.set(edge_weight_type, lit("EXPLICIT")); });
b.if_(edge_weight_type.eq("EXPLICIT"), |t| { t.check(defined(weight)).message("no EDGE_WEIGHT_SECTION"); t.check(size(weight).eq(n)) .message("edge weights do not match DIMENSION"); }) .else_(|e| { let is = |weight_type: &str| edge_weight_type.eq(weight_type); e.check(is("EUC_2D") | is("CEIL_2D") | is("ATT") | is("GEO")) .message("EDGE_WEIGHT_TYPE must be EXPLICIT, EUC_2D, CEIL_2D, ATT, or GEO"); e.check(defined(x)).message("no NODE_COORD_SECTION"); e.check(size(nodes).eq(n)) .message("coordinates do not match DIMENSION"); e.check(x.ge(-1e9) & x.le(1e9) & y.ge(-1e9) & y.le(1e9)) .message("coordinates must be between -1e9 and 1e9"); }); Ok(Tsplib { spec: b.build()?, name, n, edge_weight_type, weight, x, y, })}
fn main() -> Result<(), Box<dyn std::error::Error>> { let tsplib = tsplib()?; for case in ["explicit-five", "euc-2d-five"] { let path = format!("formats/tsplib/cases/{case}/input.txt"); let data = tsplib.spec.read_path(&path, &Params::new())?; let name: Option<&str> = data.get(tsplib.name); let n: i64 = data.get(tsplib.n); let weight_type: Option<&str> = data.get(tsplib.edge_weight_type); println!( "{}: {n} cities, {}", name.unwrap_or("unnamed"), weight_type.unwrap_or("?") ); if let Some(weight) = data.get(tsplib.weight) { for row in weight.rows() { println!(" {row:?}"); } } if let (Some(x), Some(y)) = (data.get(tsplib.x), data.get(tsplib.y)) { println!(" x {x:?}\n y {y:?}"); } } Ok(())}handmade-explicit-five: 5 cities, EXPLICIT
[0, 2, 4, 6, 3]
[2, 0, 5, 4, 7]
[4, 5, 0, 3, 6]
[6, 4, 3, 0, 2]
[3, 7, 6, 2, 0]
handmade-euc-2d-five: 5 cities, EUC_2D
x [0.0, 3.0, 3.0, 0.0, 1.5]
y [0.0, 0.0, 4.0, 4.0, 2.0]