Skip to content

C++

The iris library is a native C++23 implementation of Iris that needs only the standard library. It passes the same conformance suite as the Rust reference implementation, so it reads every input as the CLI does. The C++ API reference lists every public class and method.

Use a C++23 compiler and standard library, such as GCC 14, Clang 20 with GCC 14’s libstdc++, Apple Clang 21 or MSVC, and CMake 3.28 or newer. The library is not published yet; vcpkg and Conan packages are planned. Package versions and language versions are separate; the current library is 0.1.0 and implements Iris 0.1.

To install it, run this in the cpp directory of an Iris checkout:

Terminal window
cmake -S . -B build/release -G Ninja -DCMAKE_BUILD_TYPE=Release -DIRIS_BUILD_TESTS=OFF
cmake --build build/release
cmake --install build/release --prefix /opt/iris

A project then finds the package, with -DCMAKE_PREFIX_PATH=/opt/iris:

CMakeLists.txt
find_package(iris 0.1 REQUIRED CONFIG)
target_link_libraries(app PRIVATE iris::iris)

To build the library with your project instead, fetch a copy of the repository with FetchContent. Add SOURCE_SUBDIR cpp for a Git or archive source.

CMakeLists.txt
include(FetchContent)
FetchContent_Declare(iris SOURCE_DIR "${PROJECT_SOURCE_DIR}/third_party/iris/cpp")
FetchContent_MakeAvailable(iris)
target_link_libraries(app PRIVATE iris::iris)

A fetched copy builds no tests. It has no install rules unless you set -DIRIS_INSTALL=ON, which a project that installs targets linking iris::iris needs.

The examples on this page are in cpp/examples, and a test compiles each one, runs it and compares its output. They read files from the format library, so run them from the root of an Iris checkout.

read.cpp
#include <iris/iris.hpp>
#include <cstdint>
#include <print>
#include <span>
int main() {
const iris::Spec spec = iris::Spec::parse("n:int row[n]:int", "example.iris");
const iris::Data data = spec.read_text("3 10 20 30", "input.txt");
std::println("{}", data.integer("n"));
const std::span<const std::int64_t> row = data.ints("row");
std::println("{} {} {}", row[0], row[1], row[2]);
}
3
10 20 30

iris/iris.hpp declares the whole API. Spec::parse parses and checks a reader spec. The declaration reads n, then a row of n integers. spec.read_text reads input from memory; the origin names, such as example.iris and input.txt, appear in error messages. A Spec can read any number of inputs, and threads can read with one spec at the same time. Copies of a Spec or a Data share their contents, so they are cheap.

Spec::load reads a reader spec file, and spec.read and spec.catalog take a path. read_text and catalog_text take input from memory.

files.cpp
#include <iris/iris.hpp>
#include <filesystem>
#include <print>
int main() {
const iris::Spec spec = iris::Spec::load("formats/jobshop/jobshop.iris");
const std::filesystem::path input =
"formats/jobshop/cases/or-library/input.txt";
const iris::Data catalog = spec.catalog(input);
std::print("{}", catalog.dzn());
const iris::Params params{{"instance", "handmade-or"}};
const iris::Data data = spec.read(input, params);
std::println("{} {}", data.integer("n_jobs"), data.integer("n_machines"));
}
instances = 1;
name = ["handmade-or"];
3 3

spec.catalog lists the instances in an input as data. The instance parameter selects one instance during a read, by name or by its number, counting from 1. Params holds name and value strings, as the Specification defines: write {"instance", "2"}, not a number. params.set adds a value to existing Params.

data.size() counts the entries, and data.name(i) and data.value(i) return them in the order the reader spec defines them. data.find(name) returns an entry’s value as a std::optional.

access.cpp
#include <iris/iris.hpp>
#include <cstddef>
#include <cstdint>
#include <print>
int main() {
const iris::Spec spec =
iris::Spec::load("formats/dimacs-cnf/dimacs-cnf.iris");
const iris::Data data =
spec.read("formats/dimacs-cnf/cases/three-variables/input.txt");
for (std::size_t i = 0; i < data.size(); ++i) {
const iris::ValueRef value = data.value(i);
std::println("{} {} {}", data.name(i), iris::type_name(value.type()),
value.depth());
}
std::println("{} {}", data.find("clause").has_value(),
data.find("model").has_value());
std::println("{} {}", data.size("clause"), data.size("clause", {1}));
std::println("{}", data.integer("clause", {1, 0}));
const iris::ValueRef clauses = data.at("clause");
for (std::size_t i = 0; i < clauses.size(); ++i) {
std::print("clause {}:", i);
for (const std::int64_t literal : clauses[i].ints()) {
std::print(" {}", literal);
}
std::println("");
}
try {
std::println("{}", data.integer("clause"));
} catch (const iris::AccessError &error) {
std::println("{}", error.what());
}
}
vars int 0
clauses int 0
clause int 2
true false
3 3
2
clause 0: 1 -2
clause 1: 2 3 -1
clause 2: -3
the value is an array, not a single value

A path holds indices counted from 0, one per array level. data.size(name, path) returns the length of the array that the path selects. data.integer, data.number and data.text return a scalar, and data.ints and data.floats return a row as a std::span. data.at returns a ValueRef, a view with the same accessors, which walks a value of any depth, including arrays whose rows have different lengths and arrays of strings.

Nothing here copies. Spans, std::string_views and ValueRefs borrow from the Data, and stay valid while any copy of it exists. An unknown name, a value of another type or depth, or an index out of range throws AccessError, which is a usage error and not a language error.

data.dzn() returns the MiniZinc data of the dzn appendix. Every line ends in a newline.

output.cpp
#include <iris/iris.hpp>
#include <print>
int main() {
const iris::Spec spec =
iris::Spec::load("formats/dimacs-cnf/dimacs-cnf.iris");
const iris::Data data =
spec.read("formats/dimacs-cnf/cases/three-variables/input.txt");
std::print("{}", data.dzn());
}
vars = 3;
clauses = 3;
% clause: array[int] of tuple(array[int] of int)
clause = [([1, -2],), ([2, 3, -1],), ([-3],)];

The library has no JSON output. The canonical JSON document is the CLI’s, and the conformance driver in cpp/driver renders it for testing.

A language error is an iris::Error, which comes in two styles. Spec::parse, load, read and the catalog functions throw it. It derives from std::runtime_error, and what() is the diagnostic that Specification chapter 11 describes.

errors.cpp
#include <iris/iris.hpp>
#include <print>
int main() {
const iris::Spec spec =
iris::Spec::load("formats/dimacs-cnf/dimacs-cnf.iris");
try {
const iris::Data data =
spec.read("formats/dimacs-cnf/cases/literal-out-of-range/input.txt");
std::println("{}", data.size());
} catch (const iris::Error &error) {
std::println("{}", iris::code_name(error.code()));
std::println("{}", error.message());
const auto &location = error.input_location();
std::println("{} {}", location->line.value(), location->column.value());
std::println("{}", error.context().value());
std::println("{}", error.what());
}
}
E-EXPECTED-VALUE
expected an int in -3..3, found '4'
2 3
repeat [1 of 1] > clause
formats/dimacs-cnf/cases/literal-out-of-range/input.txt:2:3: expected an int in -3..3, found '4'
     2 | 1 4 0
       |   ^
  while reading: repeat [1 of 1] > clause
  spec: formats/dimacs-cnf/dimacs-cnf.iris:7

code() returns the ErrorCode of the stable error code, and code_name its spelling. message() is the message without a location. input_location() and spec_location() return an optional Location, whose line and column are optional too. context(), excerpt(), record_path() and earlier_rejection() are optional as well; each is present when the error has it, and details() returns them all as one ErrorDetails.

Every function that throws Error has a try_ variant that returns it in a std::expected instead:

expected.cpp
#include <iris/iris.hpp>
#include <expected>
#include <print>
int main() {
const std::expected<iris::Spec, iris::Error> rejected =
iris::Spec::try_parse("n:int row[n]:nothing", "example.iris");
if (!rejected) {
std::println("{}", iris::code_name(rejected.error().code()));
}
const iris::Spec spec = iris::Spec::parse("n:int row[n]:int", "example.iris");
const std::expected<iris::Data, iris::Error> data =
spec.try_read_text("2 10 twenty", "input.txt");
if (data) {
std::println("{}", data->integer("n"));
} else {
std::println("{}", data.error().what());
}
}
E-SPEC-UNKNOWN-TYPE
input.txt:1:6: expected int, found 'twenty'
     1 | 2 10 twenty
       |      ^
  while reading: row
  spec: example.iris:1

Both styles leave the other failures as exceptions: a file that cannot be read throws std::system_error, misuse throws AccessError, and std::bad_alloc reports exhausted memory. The language’s fixed work budgets bound every read. A read that exhausts one fails with the code E-BUDGET, and the library has no budget settings.

iris/build.hpp writes a reader spec from C++. Every statement that defines an entry returns a typed handle, an iris::Field, and data.get(handle) returns the entry as the handle’s type: a std::int64_t for n_jobs and an iris::Array<std::int64_t, 2> for machine. A builder adds no features of its own: build() prints Iris text and parses it as Spec::parse does, so the language’s checks decide what is valid, and source() returns the text.

The builders below are headers in cpp/examples, one for each format in the format library, each with a program that reads a case. A test reads every case of each format through its builder and compares the data or the error with the case’s expected results, and the example tests run each program and compare its output with the output shown here.

This builder writes the job shop reader spec.

build_jobshop.hpp
#pragma once
#include <iris/build.hpp>
#include <cstdint>
#include <string>
#include <string_view>
#include <tuple>
/// A job shop reader and the entries a scheduler needs
struct Jobshop {
iris::Spec spec;
iris::Field<std::string, 0, iris::Presence::Maybe> name;
iris::Field<std::int64_t> n_jobs;
iris::Field<std::int64_t> n_machines;
iris::Field<std::int64_t, 2> machine;
iris::Field<std::int64_t, 2> duration;
};
/// 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
inline Jobshop jobshop() {
using namespace iris::build;
constexpr std::string_view machine_twice =
"a job uses a machine twice; each job must use every machine once";
constexpr std::string_view too_long = "the total duration is too large";
SpecBuilder b("jobshop");
b.comment({"#", "+++"});
auto handles = b.instances([&](auto &i) {
auto name = i.optional_capture("name", word);
auto n_jobs = i.capture("n_jobs", Range{.from = 1});
auto n_machines = i.capture("n_machines", Range{.from = 1});
auto records = i.sections({.skip_other = true}, [&](auto &s) {
s.optional_arm(pattern("instance {}", name));
auto header = pattern("{} {}", n_jobs, n_machines);
return s.arm(header, {.last = true}, [&](auto &a) {
a.check(n_jobs <= (host::int_max - 2) / 2 / n_machines,
"there are too many jobs and machines");
return a.repeat(n_jobs, [&](auto &job) {
job.as_name("jobs"); // error messages name the records
auto steps = job.repeat(n_machines, [&](auto &step) {
return std::tuple{
step.read("machine", Range{.from = 0, .below = n_machines}),
step.read("duration", Range{.from = 0})};
});
return std::tuple_cat(std::tuple{job.record()}, steps);
});
});
});
auto [jobs, machine, duration] = records;
i.check(distinct(jobs.get(machine)), machine_twice);
auto total = sum(jobs, [&](const auto &j) { return sum(j.get(duration)); });
i.check(total <= host::int_max, too_long);
return std::tuple{name, n_jobs, n_machines, machine, duration};
});
auto [name, n_jobs, n_machines, machine, duration] = handles;
return {b.build(), name, n_jobs, n_machines, machine, duration};
}

Blocks take a lambda, which receives the block’s scope: b.instances, i.sections, s.arm and a.repeat each open one, and the statements the lambda adds go into it. Each block returns what its lambda returns, so the handles leave the blocks as a std::tuple. pattern("{} {}", n_jobs, n_machines) is a pattern whose placeholders the compiler checks against its arguments. A range is Range{.from = 0, .below = n_machines} for Iris 0..<n_machines, or Range{.from = 0, .to = n} for 0..n.

job.record() is the handle of each record of a repeat: jobs.get(machine) looks up a field, and sum(jobs, ...) writes a comprehension over the records. job.as_name("jobs") names the list of records, as in repeat n_jobs as jobs, for error messages. C++ operators build expressions, &&, || and ! included, and host::int_max is Gecode’s largest integer. Iris a ^ b is pow(a, b). Where the C library’s ::pow is declared, as MSVC’s standard headers declare it, using namespace iris::build; makes an unqualified pow ambiguous, so add using iris::build::pow; beside it. The same holds for bind in a pattern where the socket function ::bind of <sys/socket.h> or <winsock2.h> is declared: add using iris::build::bind;. On macOS, <ApplicationServices/ApplicationServices.h> declares a QuickDraw type Pattern: add using iris::build::Pattern;. Put each of these using-declarations inside a function or namespace, since at global scope it collides with the global declaration.

The program reads an instance selected by name, then a file whose check fails:

build_jobshop.cpp
#include "build_jobshop.hpp"
#include <iris/iris.hpp>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <print>
#include <span>
#include <string>
namespace {
/// `row` as `[1, 2, 3]`
std::string list(std::span<const std::int64_t> row) {
std::string text = "[";
for (std::size_t i = 0; i < row.size(); ++i)
text += (i == 0 ? "" : ", ") + std::to_string(row[i]);
return text + "]";
}
} // namespace
int main() {
const Jobshop shop = jobshop();
iris::Params params;
params.set("instance", "handmade-or");
const iris::Data data =
shop.spec.read("formats/jobshop/cases/or-library/input.txt", params);
std::println("{}: {} jobs on {} machines",
data.get(shop.name).value_or("unnamed"), data.get(shop.n_jobs),
data.get(shop.n_machines));
const auto machines = data.get(shop.machine);
const auto durations = data.get(shop.duration);
for (std::size_t job = 0; job < machines.size(); ++job) {
std::println("job {}: machines {}, durations {}", job, list(machines[job]),
list(durations[job]));
}
params.set("instance", "handmade-invalid");
try {
(void)shop.spec.read("formats/jobshop/cases/duplicate-machine/input.txt",
params);
} catch (const iris::Error &error) {
const auto &at = error.input_location();
std::println("\n{} at {}:{}:{}", iris::code_name(error.code()), at->origin,
at->line.value(), at->column.value());
std::println("{}", error.message());
// The statement's call site: the line of the distinct check in jobshop().
const auto &site = error.call_site();
const std::filesystem::path file = site->file_name();
std::println("call site: {}:{}", file.filename().string(), site->line());
}
}
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]

E-CHECK-FAILED at 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
call site: build_jobshop.hpp:52

data.get returns the view of the handle’s value type and depth: a std::int64_t for n_jobs, a std::optional<std::string_view> for name, which only some files give, and an iris::Array<std::int64_t, 2> for machine and duration, whose rows are std::span<const std::int64_t>. As with untyped access, nothing is copied. A handle names its entry, value type and depth; a lookup checks them, and throws AccessError if the entry has another type or depth.

Collecting the handles in a struct with the spec, as Jobshop does, gives the rest of a program one typed object to read with.

Every statement takes a std::source_location, which defaults to the line of the call. When a check fails while reading, the error has the input location, and error.call_site() names the line of the check in build_jobshop.hpp. A BuildError from build() has the same call site. A statement in a helper function records the line in the helper, unless the helper takes a std::source_location that defaults to its own caller’s and passes it on, as clue_lines below does.

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.

build_nonogram.hpp
#pragma once
#include <iris/build.hpp>
#include <cstdint>
#include <source_location>
#include <string_view>
#include <utility>
/// A nonogram reader: the board size and the clues of each row and column
struct Nonogram {
iris::Spec spec;
iris::Field<std::int64_t> width;
iris::Field<std::int64_t> height;
iris::Field<std::int64_t, 2> row;
iris::Field<std::int64_t, 2> col;
};
/// The clue lines of one side of the board
struct Clues {
iris::build::Record lines;
iris::Field<std::int64_t, 2> clues;
};
/// Reads `count` lines of comma-separated clues into the entry `name`. An
/// error in them names the line that calls this function.
inline Clues
clue_lines(iris::build::Scope<> &s, const iris::Field<std::int64_t> &count,
std::string_view name,
std::source_location site = std::source_location::current()) {
using namespace iris::build;
return s.repeat(
count,
[&](auto &line) {
auto clues = line.list(name, Range{.from = 0}.until(eol), site);
return Clues{line.record(), clues};
},
site);
}
/// A 0 clue says the line is empty, so it must stand alone
inline auto zero_stands_alone(const iris::Field<std::int64_t, 2> &clues) {
using namespace iris::build;
return count(clues) <= 1 || min(clues) > 0;
}
/// The clues and one gap between each pair of them fit into `length`
inline auto clues_fit(const iris::Field<std::int64_t, 2> &clues,
const iris::Field<std::int64_t> &length) {
using namespace iris::build;
return sum(clues) + count(clues) - 1 <= length;
}
inline Nonogram nonogram() {
using namespace iris::build;
SpecBuilder b("nonogram");
b.separators(",");
auto width = b.capture("width", Range{.from = 1});
auto height = b.capture("height", Range{.from = 1});
auto [rows, cols] = b.sections({.skip_other = true}, [&](auto &s) {
s.arm(pattern("width {}", width));
s.arm(pattern("height {}", height));
return std::pair{
s.arm("rows", [&](auto &a) { return clue_lines(a, height, "row"); }),
s.arm("columns", [&](auto &a) { return clue_lines(a, width, "col"); })};
});
auto row = rows.clues;
auto col = cols.clues;
b.check(height <= 1'000'000 / width,
"the board must have at most a million fields");
b.check(size(rows.lines.list()) == height && size(cols.lines.list()) == width,
"the numbers of rows and columns differ from the board size");
b.check(zero_stands_alone(row), "a 0 must be the only clue of its row");
b.check(zero_stands_alone(col), "a 0 must be the only clue of its column");
b.check(clues_fit(row, width),
"the clues of a row do not fit into the width of the board");
b.check(clues_fit(col, height),
"the clues of a column do not fit into the height of the board");
return {b.build(), width, height, row, col};
}
build_nonogram.cpp
#include "build_nonogram.hpp"
#include <iris/iris.hpp>
#include <cstddef>
#include <cstdint>
#include <print>
#include <span>
#include <string>
namespace {
/// `row` as `[1, 2, 3]`
std::string list(std::span<const std::int64_t> row) {
std::string text = "[";
for (std::size_t i = 0; i < row.size(); ++i)
text += (i == 0 ? "" : ", ") + std::to_string(row[i]);
return text + "]";
}
/// `rows` as `[[1, 2], [3]]`
std::string list(const iris::Array<std::int64_t, 2> &rows) {
std::string text = "[";
for (std::size_t i = 0; i < rows.size(); ++i)
text += (i == 0 ? "" : ", ") + list(rows[i]);
return text + "]";
}
} // namespace
int main() {
const Nonogram puzzle = nonogram();
const iris::Data data =
puzzle.spec.read("formats/nonogram/cases/five-by-five/input.txt");
std::println("{}x{} board", data.get(puzzle.width), data.get(puzzle.height));
std::println("rows: {}", list(data.get(puzzle.row)));
std::println("columns: {}", list(data.get(puzzle.col)));
}
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.

build_dimacs_cnf.hpp
#pragma once
#include <iris/build.hpp>
#include <cstdint>
/// A DIMACS CNF reader: the number of variables and one row of literals per
/// clause
struct DimacsCnf {
iris::Spec spec;
iris::Field<std::int64_t> vars;
iris::Field<std::int64_t, 2> clause;
};
inline DimacsCnf dimacs_cnf() {
using namespace iris::build;
SpecBuilder b("dimacs-cnf");
b.comment("c");
b.stop("%"); // SATLIB files end with "%" and "0"
auto variables = b.capture("vars", Range{.from = 0, .to = host::int_max});
auto clauses = b.capture("clauses", Range{.from = 0});
b.line(pattern("p cnf {} {}", variables, clauses));
auto clause = b.repeat(clauses, [&](auto &c) {
// The terminating 0 is not stored.
return c.list("clause",
Range{.from = -variables, .to = variables}.until(0));
});
return {b.build(), variables, clause};
}
build_dimacs_cnf.cpp
#include "build_dimacs_cnf.hpp"
#include <iris/iris.hpp>
#include <cstddef>
#include <cstdint>
#include <print>
#include <span>
#include <string>
namespace {
/// `row` as `[1, 2, 3]`
std::string list(std::span<const std::int64_t> row) {
std::string text = "[";
for (std::size_t i = 0; i < row.size(); ++i)
text += (i == 0 ? "" : ", ") + std::to_string(row[i]);
return text + "]";
}
} // namespace
int main() {
const DimacsCnf cnf = dimacs_cnf();
const iris::Data data =
cnf.spec.read("formats/dimacs-cnf/cases/three-variables/input.txt");
std::println("{} variables", data.get(cnf.vars));
for (const std::span<const std::int64_t> clause : data.get(cnf.clause))
std::println("{}", list(clause));
}
3 variables
[1, -2]
[2, 3, -1]
[-3]
build_sudoku.hpp
#pragma once
#include <iris/build.hpp>
#include <cstdint>
#include <string_view>
#include <tuple>
/// A Sudoku reader: the grid size, the box size, and the cells, with 0 for a
/// blank
struct Sudoku {
iris::Spec spec;
iris::Field<std::int64_t> n;
iris::Field<std::int64_t> box_width;
iris::Field<std::int64_t> box_height;
iris::Field<std::int64_t, 2> cells;
};
/// Cell values from 1 to 36, so `1` reads as 1 and `0` as 36
inline constexpr std::string_view sudoku_symbols =
"123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0";
inline Sudoku sudoku() {
using namespace iris::build;
SpecBuilder b("sudoku");
auto handles = b.instances([](auto &i) {
auto n = i.capture("n", Range{.from = 1});
auto box_width = i.capture("box_width", Range{.from = 1});
auto box_height = i.capture("box_height", Range{.from = 1});
i.line(pattern("# size={} box={}x{}", n, box_width, box_height));
auto cells =
i.read("cells", alphabet(sudoku_symbols).blank(".").dim(n).dim(n));
i.check(box_width * box_height == n, "boxes must tile the grid");
i.check(max(cells) <= n, "a value is larger than the size of the grid");
return std::tuple{n, box_width, box_height, cells};
});
auto [n, box_width, box_height, cells] = handles;
return {b.build(), n, box_width, box_height, cells};
}
build_sudoku.cpp
#include "build_sudoku.hpp"
#include <iris/iris.hpp>
#include <cstddef>
#include <cstdint>
#include <print>
#include <span>
#include <string>
namespace {
/// `row` as `[1, 2, 3]`
std::string list(std::span<const std::int64_t> row) {
std::string text = "[";
for (std::size_t i = 0; i < row.size(); ++i)
text += (i == 0 ? "" : ", ") + std::to_string(row[i]);
return text + "]";
}
} // namespace
int main() {
const Sudoku puzzle = sudoku();
const iris::Data data =
puzzle.spec.read("formats/sudoku/cases/four-by-four/input.txt");
const std::int64_t n = data.get(puzzle.n);
std::println("{}x{} grid with {}x{} boxes", n, n, data.get(puzzle.box_width),
data.get(puzzle.box_height));
for (const std::span<const std::int64_t> row : data.get(puzzle.cells))
std::println("{}", list(row));
}
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:

build_tsptw.hpp
#pragma once
#include <iris/build.hpp>
#include <cstdint>
#include <tuple>
/// 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
struct Tsptw {
iris::Spec spec;
iris::Field<std::int64_t> n;
iris::Field<std::int64_t, 2> dist;
iris::Field<std::int64_t, 1> ready;
iris::Field<std::int64_t, 1> due;
};
inline Tsptw tsptw() {
using namespace iris::build;
SpecBuilder b("tsptw");
b.comment("#");
auto n = b.read("n", Range{.from = 2, .to = 1000});
auto distance = Range{.from = 0, .to = host::int_max / 2 / n};
auto dist = b.read("dist", distance.dim(n).dim(n));
auto time = b.define_type("time", Range{.from = 0, .to = host::int_max / 2});
auto [nodes, ready, due] = b.repeat(n, [&](auto &node) {
node.as_name("nodes");
return std::tuple{node.record(), node.read("ready", time),
node.read("due", time)};
});
b.check(nodes.get(ready) <= nodes.get(due),
"the time window of a node is invalid");
b.check(nodes.list()[0].get(ready) == 0,
"the depot (node 0) must open at time 0");
return {b.build(), n, dist, ready, due};
}
build_tsptw.cpp
#include "build_tsptw.hpp"
#include <iris/iris.hpp>
#include <cstddef>
#include <cstdint>
#include <print>
#include <span>
#include <string>
namespace {
/// `row` as `[1, 2, 3]`
std::string list(std::span<const std::int64_t> row) {
std::string text = "[";
for (std::size_t i = 0; i < row.size(); ++i)
text += (i == 0 ? "" : ", ") + std::to_string(row[i]);
return text + "]";
}
} // namespace
int main() {
const Tsptw problem = tsptw();
const iris::Data data =
problem.spec.read("formats/tsptw/cases/three-nodes/input.txt");
std::println("{} nodes", data.get(problem.n));
const auto dist = data.get(problem.dist);
const std::span<const std::int64_t> ready = data.get(problem.ready);
const std::span<const std::int64_t> due = data.get(problem.due);
for (std::size_t node = 0; node < dist.size(); ++node) {
std::println("node {}: open {}..{}, distances {}", node, ready[node],
due[node], list(dist[node]));
}
}
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. t.set gives an optional entry a default while keeping its handle’s type, b.if_ and its else_ take the checks that apply to each kind of file, and one_of is an ordinary C++ function template that builds an expression:

build_tsplib.hpp
#pragma once
#include <iris/build.hpp>
#include <cstdint>
#include <source_location>
#include <string>
#include <string_view>
/// A TSPLIB reader. A file gives either an explicit distance matrix or node
/// coordinates, from which the distances follow.
struct Tsplib {
iris::Spec spec;
iris::Field<std::string, 0, iris::Presence::Maybe> name;
iris::Field<std::int64_t> n;
iris::Field<std::string, 0, iris::Presence::Maybe> edge_weight_type;
iris::Field<std::int64_t, 2, iris::Presence::Maybe> weight;
iris::Field<double, 1, iris::Presence::Maybe> x;
iris::Field<double, 1, iris::Presence::Maybe> y;
};
/// The entries of one section of numbered coordinates
struct Coordinates {
iris::build::Record nodes;
iris::Field<double, 1, iris::Presence::Maybe> x;
iris::Field<double, 1, iris::Presence::Maybe> y;
};
/// Whether `entry` is one of `values`: `entry == "A" || entry == "B"`
template <class... Values>
auto one_of(const iris::Field<std::string, 0, iris::Presence::Maybe> &entry,
std::string_view first, Values... rest) {
return ((entry == first) || ... || (entry == std::string_view(rest)));
}
/// Adds the optional section `title` of `n` lines `node x y`, with the
/// entries named `{prefix}node`, `{prefix}x` and `{prefix}y`
inline Coordinates coordinate_section(
iris::build::Arms<> &arms, std::string_view title,
const iris::Field<std::int64_t> &n, const std::string &prefix,
std::source_location site = std::source_location::current()) {
using namespace iris::build;
return arms.optional_arm(
Pattern().text(title),
[&](auto &a) {
return a.repeat(
n,
[&](auto &line) {
line.read(prefix + "node", int_, site);
return Coordinates{line.record(),
line.read(prefix + "x", float_, site),
line.read(prefix + "y", float_, site)};
},
site);
},
site);
}
inline Tsplib tsplib() {
using namespace iris::build;
SpecBuilder b("tsplib");
b.comment("COMMENT");
auto name = b.optional_capture("name", rest);
auto problem_type = b.optional_capture("type", word);
auto n = b.capture("n", Range{.from = 2, .to = 46340});
auto edge_weight_type = b.optional_capture("edge_weight_type", word);
auto edge_weight_format = b.optional_capture("edge_weight_format", word);
auto node_coord_type = b.optional_capture("node_coord_type", word);
auto display_data_type = b.optional_capture("display_data_type", word);
auto [coordinates, weight] = b.sections({.until = "EOF"}, [&](auto &s) {
s.optional_arm(pattern("NAME : {}", name));
s.optional_arm(pattern("TYPE : {}", problem_type));
s.arm(pattern("DIMENSION : {}", n));
s.optional_arm(pattern("EDGE_WEIGHT_TYPE : {}", edge_weight_type));
s.optional_arm(pattern("EDGE_WEIGHT_FORMAT : {}", edge_weight_format));
s.optional_arm(pattern("NODE_COORD_TYPE : {}", node_coord_type));
s.optional_arm(pattern("DISPLAY_DATA_TYPE : {}", display_data_type));
auto nodes = coordinate_section(s, "NODE_COORD_SECTION", n, "");
auto weights = s.optional_arm("EDGE_WEIGHT_SECTION", [&](auto &a) {
a.if_(!defined(edge_weight_format),
[&](auto &t) { t.set(edge_weight_format, "FULL_MATRIX"); });
auto bound = host::int_max / n;
return a.read("weight",
Range{.from = 0, .to = bound}.dim(n).dim(n).layout(
edge_weight_format));
});
coordinate_section(s, "DISPLAY_DATA_SECTION", n, "display_");
return std::pair{nodes, weights};
});
b.if_(!defined(edge_weight_type),
[&](auto &t) { t.set(edge_weight_type, "EXPLICIT"); });
auto x = coordinates.x;
auto y = coordinates.y;
b.if_(edge_weight_type == "EXPLICIT", [&](auto &t) {
t.check(defined(weight), "no EDGE_WEIGHT_SECTION");
t.check(size(weight) == n, "edge weights do not match DIMENSION");
}).else_([&](auto &e) {
e.check(one_of(edge_weight_type, "EUC_2D", "CEIL_2D", "ATT", "GEO"),
"EDGE_WEIGHT_TYPE must be EXPLICIT, EUC_2D, CEIL_2D, ATT, or GEO");
e.check(defined(x), "no NODE_COORD_SECTION");
e.check(size(coordinates.nodes.list()) == n,
"coordinates do not match DIMENSION");
e.check(x >= -1e9 && x <= 1e9 && y >= -1e9 && y <= 1e9,
"coordinates must be between -1e9 and 1e9");
});
return {b.build(), name, n, edge_weight_type, weight, x, y};
}
build_tsplib.cpp
#include "build_tsplib.hpp"
#include <iris/iris.hpp>
#include <cstddef>
#include <format>
#include <print>
#include <span>
#include <string>
namespace {
/// `row` as `[1, 2, 3]`
template <class T> std::string list(std::span<const T> row) {
std::string text = "[";
for (std::size_t i = 0; i < row.size(); ++i)
text += std::format("{}{}", i == 0 ? "" : ", ", row[i]);
return text + "]";
}
} // namespace
int main() {
const Tsplib problem = tsplib();
for (const char *example : {"explicit-five", "euc-2d-five"}) {
const iris::Data data = problem.spec.read(
std::format("formats/tsplib/cases/{}/input.txt", example));
std::println(
"{}: {} cities, {}", data.get(problem.name).value_or("unnamed"),
data.get(problem.n), data.get(problem.edge_weight_type).value_or("?"));
if (const auto weight = data.get(problem.weight)) {
for (const std::span<const std::int64_t> row : *weight)
std::println(" {}", list(row));
}
const auto x = data.get(problem.x);
const auto y = data.get(problem.y);
if (x && y)
std::println(" x {}\n y {}", list(*x), list(*y));
}
}
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, 3, 3, 0, 1.5]
  y [0, 0, 4, 4, 2]

A reader spec written as an .iris file has no builder, but iris gen --lang cpp SPEC prints a header with a typed handle for each of its entries, in a namespace named after the spec’s file:

Terminal window
iris gen --lang cpp formats/jobshop/jobshop.iris
// Typed handles of a reader spec, generated by `iris gen --lang cpp`.
#pragma once

#include <iris/handle.hpp>

#include <cstdint>
#include <string>

namespace jobshop {

inline constexpr iris::Field<std::string, 0, iris::Presence::Maybe> name{
    "name"};
inline constexpr iris::Field<std::int64_t> n_jobs{"n_jobs"};
inline constexpr iris::Field<std::int64_t> n_machines{"n_machines"};
inline constexpr iris::Field<std::int64_t, 2> machine{"machine"};
inline constexpr iris::Field<std::int64_t, 2> duration{"duration"};

} // namespace jobshop

Save the output as a header, such as jobshop_view.hpp, and read data with data.get(jobshop::machine) as with a builder’s handles. An entry whose value type or depth differs between the places that define it gets an iris::DynField, which returns an optional ValueRef.

Every allocation the library makes comes from a std::pmr::memory_resource, so a host can supply its own heap. Spec::parse and Spec::load take one as their last argument, the default resource unless given. The spec, every read with it and the data they return allocate from it:

memory.cpp
#include <iris/iris.hpp>
#include <cstddef>
#include <memory_resource>
#include <print>
// Passes every allocation on to the default resource, and counts the bytes
// that are allocated and not yet returned.
class CountingResource : public std::pmr::memory_resource {
public:
[[nodiscard]] std::size_t held() const { return held_; }
private:
void *do_allocate(std::size_t bytes, std::size_t alignment) override {
held_ += bytes;
return upstream_->allocate(bytes, alignment);
}
void do_deallocate(void *pointer, std::size_t bytes,
std::size_t alignment) override {
held_ -= bytes;
upstream_->deallocate(pointer, bytes, alignment);
}
[[nodiscard]] bool
do_is_equal(const std::pmr::memory_resource &other) const noexcept override {
return this == &other;
}
std::pmr::memory_resource *upstream_ = std::pmr::get_default_resource();
std::size_t held_ = 0;
};
int main() {
CountingResource memory;
{
const iris::Spec spec =
iris::Spec::parse("n:int row[n]:int", "example.iris", memory);
const iris::Data data = spec.read_text("3 10 20 30", "input.txt");
std::println("{} {}", data.integer("n"), memory.held() > 0);
}
std::println("{}", memory.held());
}
3 true
0

Params takes its own resource when it is constructed. The resource must outlive the spec, the parameters and the data, and it must be thread-safe if threads read with one spec at the same time. Errors leave the library, so Error, AccessError and std::system_error use the global heap. Reading a file opens it with the C library, whose FILE may come from malloc.