Skip to content

Java and Kotlin

The iris library is a native Java implementation of Iris. Its only dependency is the JSpecify annotations. It passes the same conformance suite as the Rust reference implementation, so it reads every input as the CLI does. The Java API reference lists every public class and method, and the Kotlin API reference lists the extensions and the Kotlin spec builder.

The library needs Java 27. It is not on Maven Central yet; publication is planned. Package versions and language versions are separate; the current library is 0.1.0 and implements Iris 0.1.

Until then, build it from a checkout. With Java 27 installed, run this in the java directory of an Iris checkout, which installs both modules in your local Maven repository:

Terminal window
./gradlew publishToMavenLocal

A Gradle project then uses the coordinates dev.gecode:iris:0.1.0. Once the library is published, mavenLocal() can go:

build.gradle.kts
repositories {
mavenLocal()
mavenCentral()
}
java { toolchain { languageVersion = JavaLanguageVersion.of(27) } }
dependencies {
implementation("dev.gecode:iris:0.1.0")
}

A Maven project adds the same coordinates, and sets maven.compiler.release to 27:

pom.xml
<dependency>
<groupId>dev.gecode</groupId>
<artifactId>iris</artifactId>
<version>0.1.0</version>
</dependency>

The jar is the module dev.gecode.iris, so a modular application writes requires dev.gecode.iris;, and it also works on the class path.

The examples on this page are in java/iris-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.java
package examples;
import dev.gecode.iris.Data;
import dev.gecode.iris.Spec;
import java.util.Arrays;
public final class Read {
public static void main(String[] args) {
Spec spec = Spec.parse("n:int row[n]:int", "example.iris");
Data data = spec.read("3 10 20 30", "input.txt");
System.out.println(data.get("n").asLong());
System.out.println(Arrays.toString(data.get("row").longs()));
}
}
3
[10, 20, 30]

Spec.parse parses and checks a reader spec. The declaration reads n, then a row of n integers. spec.read reads input from a String, a byte[] or a Path; the origin names, such as example.iris and input.txt, appear in error messages. A Spec can read any number of inputs.

Spec.parse takes the bytes of a reader spec, so read the file yourself. spec.read and spec.catalog take a Path directly, and its text is the origin. They wrap an IOException in an UncheckedIOException.

Instances.java
package examples;
import dev.gecode.iris.Data;
import dev.gecode.iris.Params;
import dev.gecode.iris.Spec;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public final class Instances {
public static void main(String[] args) throws IOException {
Spec spec = Spec.parse(Files.readAllBytes(Path.of("formats/jobshop/jobshop.iris")));
Path input = Path.of("formats/jobshop/cases/or-library/input.txt");
Data catalog = spec.catalog(input);
System.out.print(catalog.toDzn());
Data data = spec.read(input, Params.of("instance", "handmade-or"));
System.out.println(data.get("n_jobs").asLong() + " " + data.get("n_machines").asLong());
}
}
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 Params.of("instance", "2"), not a number. Params.of also takes a Map, and params.with returns Params with one more value.

data.entries() returns the entries in the order the reader spec defines them, as records of a name and a Value. data.get(name) returns an entry’s value, and data.find(name) returns it or null.

Access.java
package examples;
import dev.gecode.iris.Data;
import dev.gecode.iris.Spec;
import dev.gecode.iris.Value;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
public final class Access {
public static void main(String[] args) throws IOException {
Spec spec = Spec.parse(Files.readAllBytes(Path.of("formats/dimacs-cnf/dimacs-cnf.iris")));
Data data = spec.read(Path.of("formats/dimacs-cnf/cases/three-variables/input.txt"));
for (Data.Entry entry : data.entries()) {
Value value = entry.value();
System.out.println(entry.name() + " " + value.type().text() + " " + value.depth());
}
System.out.println((data.find("clause") != null) + " " + (data.find("model") != null));
Value clauses = data.get("clause");
System.out.println(clauses.size() + " " + clauses.get(1).size());
System.out.println(clauses.at(1, 0).asLong());
for (int i = 0; i < clauses.size(); i++) {
System.out.println("clause " + i + ": " + Arrays.toString(clauses.get(i).ints()));
}
System.out.println(describe(data.get("vars")));
System.out.println(describe(clauses));
try {
System.out.println(clauses.asLong());
} catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
}
private static String describe(Value value) {
return switch (value) {
case Value.IntValue(long integer) -> "the integer " + integer;
case Value.FloatValue(double number) -> "the float " + number;
case Value.StringValue(String text) -> "the string " + text;
case Value.ArrayValue array -> "an array of " + array.size();
};
}
}
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 integer 3
an array of 3
the value is an array, not a single value

asLong, asDouble and asString return a single value. size, get and at walk an array, including arrays whose rows have different lengths; at takes one index per level, counted from 0. longs, ints and doubles return a one-dimensional row as a new primitive array on each call, and strings an unmodifiable list. ints throws ArithmeticException for an integer that does not fit an int.

Value is sealed, so a switch over it needs no default. Asking a Value for something it is not, or asking data.get for an unknown name, throws IllegalStateException or IndexOutOfBoundsException. These are mistakes in the calling code and never an IrisException.

data.toDzn() returns the MiniZinc data of the dzn appendix, and data.toJson() the canonical JSON document of the data model. Every line ends in a newline.

Output.java
package examples;
import dev.gecode.iris.Data;
import dev.gecode.iris.Spec;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public final class Output {
public static void main(String[] args) throws IOException {
Spec spec = Spec.parse(Files.readAllBytes(Path.of("formats/dimacs-cnf/dimacs-cnf.iris")));
Data data = spec.read(Path.of("formats/dimacs-cnf/cases/three-variables/input.txt"));
System.out.print(data.toDzn());
System.out.print(data.toJson());
}
}
vars = 3;
clauses = 3;
% clause: array[int] of tuple(array[int] of int)
clause = [([1, -2],), ([2, 3, -1],), ([-3],)];
{"iris":"0.1","entries":[{"name":"vars","type":"int","depth":0,"value":3},{"name":"clauses","type":"int","depth":0,"value":3},{"name":"clause","type":"int","depth":2,"value":[[1,-2],[2,3,-1],[-3]]}]}

A language error is an IrisException, an unchecked exception that Spec.parse, spec.read and spec.catalog throw. getMessage() is the diagnostic that Specification chapter 11 describes.

Errors.java
package examples;
import dev.gecode.iris.ErrorCode;
import dev.gecode.iris.IrisError;
import dev.gecode.iris.IrisException;
import dev.gecode.iris.Spec;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public final class Errors {
public static void main(String[] args) throws IOException {
String specPath = "formats/dimacs-cnf/dimacs-cnf.iris";
String inputPath = "formats/dimacs-cnf/cases/literal-out-of-range/input.txt";
Spec spec = Spec.parse(Files.readAllBytes(Path.of(specPath)), specPath);
try {
spec.read(Files.readAllBytes(Path.of(inputPath)), inputPath);
} catch (IrisException e) {
System.out.println(e.code().code());
System.out.println(e.code() == ErrorCode.EXPECTED_VALUE);
System.out.println(e.error().message());
System.out.println(e.line() + " " + e.column());
System.out.println(e.error().context());
System.out.println(stage(e.error()));
System.out.println(e.getMessage());
}
}
private static String stage(IrisError error) {
return switch (error) {
case IrisError.SpecError e -> "the reader spec is wrong";
case IrisError.ReadError e -> "the input does not match";
case IrisError.CheckError e -> "a check failed at " + e.recordPath();
};
}
}
E-EXPECTED-VALUE
true
expected an int in -3..3, found '4'
2 3
repeat [1 of 1] > clause
the input does not match
formats/dimacs-cnf/cases/literal-out-of-range/input.txt:2:3: expected an int in -3..3, found '4'

code() returns the ErrorCode of the stable error code, and its code() the spelling. Compare codes, not messages. origin(), line() and column() give the location in the input if the error has one, and otherwise in the reader spec; each can be null. path() gives the indices of a failed check’s witness.

error() returns the IrisError with all the details: message(), inputLocation(), specLocation(), context() and recordPath(), and toJson() for the canonical error document. It is sealed, with one record for each of SpecError, ReadError and CheckError.

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.

The module dev.gecode:iris-kotlin adds extensions to the Java API. It depends on dev.gecode:iris and the Kotlin standard library, and nothing else. It is not on Maven Central yet either; the command above installs it too.

build.gradle.kts
dependencies {
implementation("dev.gecode:iris-kotlin:0.1.0")
}

In Maven:

pom.xml
<dependency>
<groupId>dev.gecode</groupId>
<artifactId>iris-kotlin</artifactId>
<version>0.1.0</version>
</dependency>

The module still needs Java 27 to run, but Kotlin has no JVM 27 target yet, so its classes target JVM 26. A Kotlin project does the same. On Java 27, Gradle would otherwise reject the difference between the Java and Kotlin targets:

build.gradle.kts
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
import org.jetbrains.kotlin.gradle.dsl.jvm.JvmTargetValidationMode
import org.jetbrains.kotlin.gradle.tasks.KotlinJvmCompile
kotlin { compilerOptions { jvmTarget = JvmTarget.JVM_26 } }
tasks.withType<KotlinJvmCompile>().configureEach {
jvmTargetValidationMode = JvmTargetValidationMode.IGNORE
}

The Java API works from Kotlin as it is. data["n"] and value[0] call the Java get methods as operators.

Read.kt
package examples
import dev.gecode.iris.Spec
import dev.gecode.iris.kotlin.toLongArray
fun main() {
val spec = Spec.parse("n:int row[n]:int", "example.iris")
val data = spec.read("3 10 20 30", "input.txt")
println(data["n"].asLong())
println(data["row"].toLongArray().joinToString(" "))
}
3
10 20 30

The Java API is @NullMarked, so Kotlin sees non-null types, and a result marked @Nullable, such as that of data.find, as nullable. The extensions add indexing by several levels at once, arrays and sequences:

Extensions.kt
package examples
import dev.gecode.iris.Spec
import dev.gecode.iris.kotlin.asSequence
import dev.gecode.iris.kotlin.get
import dev.gecode.iris.kotlin.leaves
import dev.gecode.iris.kotlin.toIntArray
import dev.gecode.iris.kotlin.toParams
import java.nio.file.Files
import java.nio.file.Path
fun main() {
val dimacs = Spec.parse(Files.readAllBytes(Path.of("formats/dimacs-cnf/dimacs-cnf.iris")))
val data = dimacs.read(Path.of("formats/dimacs-cnf/cases/three-variables/input.txt"))
for (entry in data.asSequence()) {
println("${entry.name} ${entry.value.type().text()} ${entry.value.depth()}")
}
println(data.find("model")?.size() ?: "no model")
val clauses = data["clause"]
println(clauses[1][0].asLong())
println(clauses[1, 0].asLong())
val row: IntArray = clauses[1].toIntArray()
println(row.sum())
println(clauses.asSequence().maxOf { clause -> clause.size() })
println(clauses.leaves().count())
val jobshop = Spec.parse(Files.readAllBytes(Path.of("formats/jobshop/jobshop.iris")))
val input = Path.of("formats/jobshop/cases/or-library/input.txt")
val params = mapOf("instance" to "handmade-or").toParams()
println(jobshop.read(input, params)["n_jobs"].asLong())
}
vars int 0
clauses int 0
clause int 2
no model
2
2
4
3
6
3

value[i, j] selects what value.at(i, j) does. toIntArray, toLongArray and toDoubleArray return a new array, and toIntArray throws ArithmeticException as ints does. asSequence walks the elements of an array or the entries of Data, leaves the single values at any depth in row order, and toParams makes Params from a map. Misuse throws what the Java API throws.

IrisError is sealed in Kotlin as well, so a when over it needs no else:

Errors.kt
package examples
import dev.gecode.iris.IrisError
import dev.gecode.iris.IrisException
import dev.gecode.iris.Spec
fun main() {
try {
Spec.parse("n:int", "example.iris").read("many", "input.txt")
} catch (e: IrisException) {
println(e.code().code())
println("${e.line()}:${e.column()}")
println(
when (val error = e.error()) {
is IrisError.SpecError -> "the reader spec is wrong"
is IrisError.ReadError -> "the input does not match"
is IrisError.CheckError -> "a check failed at ${error.recordPath()}"
}
)
}
}
E-EXPECTED-VALUE
1:1
the input does not match

dev.gecode.iris.build writes a reader spec from Java. A handle names an entry with its value type and depth: int0("n_jobs") is an IntField<Long> and int2("machine") an IntField<List<long[]>>. Statements use the handles, and after a read data.get(handle) returns the entry as the handle’s type. A builder adds no features of its own: spec(...) prints Iris text and parses it as Spec.parse does, so the language’s checks decide what is valid, and builder(...).source() returns the text. The spec builder reference lists its classes.

The builders below are in java/iris-examples, one for each format in the format library, in Java and in Kotlin, each with a program that reads a case. A test reads every case of each format through both builders 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, and its program reads an instance selected by name, then the same entries into a record, then a file whose check fails:

BuildJobshop.java
package examples;
import static dev.gecode.iris.build.Iris.*;
import dev.gecode.iris.Data;
import dev.gecode.iris.Entry;
import dev.gecode.iris.IrisException;
import dev.gecode.iris.Params;
import dev.gecode.iris.RecordReader;
import dev.gecode.iris.Spec;
import dev.gecode.iris.build.Gecode;
import dev.gecode.iris.build.IntField;
import dev.gecode.iris.build.RecordName;
import dev.gecode.iris.build.StringField;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import org.jspecify.annotations.Nullable;
/** A job shop reader and the entries a scheduler needs. */
public final class BuildJobshop {
public static final StringField<@Nullable String> name = string0("name").optional();
public static final IntField<Long> nJobs = int0("n_jobs");
public static final IntField<Long> nMachines = int0("n_machines");
public static final IntField<List<long[]>> machine = int2("machine");
public static final IntField<List<long[]>> duration = int2("duration");
// Error messages name the records of the jobs.
private static final RecordName job = recordName("job", "jobs");
/**
* 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.
*/
public static final Spec spec =
spec(
"jobshop",
() -> {
comment("#", "+++");
instances(() -> {
sections(
skipOther(),
() -> {
arm(pattern("instance ", capture(name, word())), optional());
var header =
pattern(capture(nJobs, atLeast(1)), " ", capture(nMachines, atLeast(1)));
arm(
header,
last(),
() -> {
check(
nJobs.le(Gecode.intMax.minus(2).div(2).div(nMachines)),
"there are too many jobs and machines");
repeat(
nJobs,
job,
() ->
repeat(
nMachines,
() -> {
read(machine, range(0).below(nMachines));
read(duration, atLeast(0));
}));
});
});
check(
distinct(job.get(machine)),
"a job uses a machine twice; each job must use every machine once");
check(
sum(job, j -> sum(j.get(duration))).le(Gecode.intMax),
"the total duration is too large");
});
});
/** The same entries as a record, whose components name them. */
record Shop(
@Nullable String name,
@Entry("n_jobs") long nJobs,
@Entry("n_machines") long nMachines,
List<long[]> machine,
List<long[]> duration) {}
private BuildJobshop() {}
public static void main(String[] args) throws IOException {
Path orLibrary = Path.of("formats/jobshop/cases/or-library/input.txt");
Data data = spec.read(orLibrary, Params.of("instance", "handmade-or"));
String shop = data.get(name);
System.out.printf(
"%s: %d jobs on %d machines%n",
shop == null ? "unnamed" : shop, data.get(nJobs), data.get(nMachines));
List<long[]> machines = data.get(machine);
List<long[]> durations = data.get(duration);
for (int j = 0; j < machines.size(); j++) {
System.out.printf(
"job %d: machines %s, durations %s%n",
j, Arrays.toString(machines.get(j)), Arrays.toString(durations.get(j)));
}
RecordReader<Shop> reader = spec.reader(Shop.class, MethodHandles.lookup());
Shop jsplib = reader.read(Path.of("formats/jobshop/cases/jsplib/input.txt"));
System.out.printf(
"%n%s: %d jobs, first job on machines %s%n",
jsplib.name() == null ? "unnamed" : jsplib.name(),
jsplib.nJobs(),
Arrays.toString(jsplib.machine().get(0)));
// Errors name a path's input with the platform's separators, so this read
// names the input itself to print the same on every platform.
String invalid = "formats/jobshop/cases/duplicate-machine/input.txt";
try {
var _ =
spec.read(
Files.readAllBytes(Path.of(invalid)),
invalid,
Params.of("instance", "handmade-invalid"));
} catch (IrisException error) {
System.out.printf(
"%n%s at %s:%d:%d%n", error.code().code(), error.origin(), error.line(), error.column());
System.out.println(error.error().message());
// The statement's call site: the line of the distinct check above.
StackTraceElement site = error.callSite().orElseThrow();
System.out.println("call site: " + site.getFileName() + ":" + site.getLineNumber());
}
}
}
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]

unnamed: 3 jobs, first job on machines [0, 2, 1]

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: BuildJobshop.java:69

The handles are constants, and spec is a constant built from them. With import static dev.gecode.iris.build.Iris.*, the statements read like the spec: blocks take a lambda, and the statements it makes go into the block, so instances, sections, arm and repeat nest as their Iris blocks do. capture(nJobs, atLeast(1)) puts a field into a pattern, and range(0).below(nMachines) is Iris 0..<n_machines. Methods such as le, minus and div build expressions, and Gecode.intMax is Gecode’s largest integer.

recordName("job", "jobs") names each record of a repeat and the list of records, as in repeat n_jobs as jobs with each job, for error messages and comprehensions: job.get(machine) looks up a field of each record, and sum(job, j -> ...) writes a comprehension over them.

data.get returns what the handle’s type says: a Long for nJobs, a nullable String for name, which only some files give, and a List<long[]> for machine and duration, with a long[] for each job. A lookup checks the entry’s value type, depth and presence, and throws IllegalStateException if they differ from the handle’s.

spec.reader(Shop.class, MethodHandles.lookup()) reads the same entries into a record. Each component names its entry, or takes the name from @Entry, and its type decides the value as a handle’s does; a long component reads a required integer. reader checks the components against the spec’s entries, and throws IllegalArgumentException for one that names no entry or does not fit its entry, so a read can fail only as spec.read does.

A builder records where each statement was made. When a check fails while reading, the error has the input location, and error.callSite() names the line of the check in BuildJobshop.java, in your code rather than in the library. A BuildException from spec(...) has the same call site. A statement made in a helper method records the line in the helper.

A method that makes statements is a reusable piece of a reader spec. The nonogram builder reads the clues of the rows and of the columns with one helper, clueLines, and builds two pairs of checks with two expression helpers:

BuildNonogram.java
package examples;
import static dev.gecode.iris.build.Iris.*;
import dev.gecode.iris.Data;
import dev.gecode.iris.Spec;
import dev.gecode.iris.build.IntExpr;
import dev.gecode.iris.build.IntField;
import dev.gecode.iris.build.RecordName;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/** A nonogram reader: the board size and the clues of each row and column. */
public final class BuildNonogram {
public static final IntField<Long> width = int0("width");
public static final IntField<Long> height = int0("height");
public static final IntField<List<long[]>> row = int2("row");
public static final IntField<List<long[]>> col = int2("col");
// The lines of each kind, which the size check counts.
private static final RecordName rows = recordName();
private static final RecordName cols = recordName();
public static final Spec spec =
spec(
"nonogram",
() -> {
separators(",");
sections(
skipOther(),
() -> {
arm(pattern("width ", capture(width, atLeast(1))));
arm(pattern("height ", capture(height, atLeast(1))));
arm("rows", () -> clueLines(height, rows, row));
arm("columns", () -> clueLines(width, cols, col));
});
check(
height.le(lit(1_000_000).div(width)),
"the board must have at most a million fields");
check(
size(rows.list()).eq(height).and(size(cols.list()).eq(width)),
"the numbers of rows and columns differ from the board size");
check(zeroStandsAlone(row), "a 0 must be the only clue of its row");
check(zeroStandsAlone(col), "a 0 must be the only clue of its column");
check(
cluesFit(row, width), "the clues of a row do not fit into the width of the board");
check(
cluesFit(col, height),
"the clues of a column do not fit into the height of the board");
});
private BuildNonogram() {}
/** Reads {@code count} lines of comma-separated clues into {@code clues}. */
static void clueLines(IntField<Long> count, RecordName lines, IntField<List<long[]>> clues) {
repeat(count, lines, () -> list(clues, atLeast(0).untilEol()));
}
/** A 0 clue says the line is empty, so it must stand alone. */
static IntExpr zeroStandsAlone(IntField<List<long[]>> clues) {
return count(clues).le(1).or(min(clues).gt(0));
}
/** The clues and one gap between each pair of them fit into {@code length}. */
static IntExpr cluesFit(IntField<List<long[]>> clues, IntField<Long> length) {
return sum(clues).plus(count(clues)).minus(1).le(length);
}
public static void main(String[] args) {
Data data = spec.read(Path.of("formats/nonogram/cases/five-by-five/input.txt"));
System.out.println(data.get(width) + "x" + data.get(height) + " board");
System.out.println("rows: " + rows(data.get(row)));
System.out.println("columns: " + rows(data.get(col)));
}
/** {@code rows} as {@code [[1, 2], [3]]}. */
private static String rows(List<long[]> rows) {
return rows.stream().map(Arrays::toString).collect(Collectors.joining(", ", "[", "]"));
}
}
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 spec(...) instead of quietly replacing an entry. That is why clueLines takes its handle from its caller. The TSPLIB builder below uses the same idea for its two coordinate sections.

BuildDimacsCnf.java
package examples;
import static dev.gecode.iris.build.Iris.*;
import dev.gecode.iris.Data;
import dev.gecode.iris.Spec;
import dev.gecode.iris.build.Gecode;
import dev.gecode.iris.build.IntField;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
/** A DIMACS CNF reader: the number of variables and one row of literals per clause. */
public final class BuildDimacsCnf {
public static final IntField<Long> vars = int0("vars");
public static final IntField<Long> clauses = int0("clauses");
public static final IntField<List<long[]>> clause = int2("clause");
public static final Spec spec =
spec(
"dimacs-cnf",
() -> {
comment("c");
stop("%"); // SATLIB files end with "%" and "0"
line(
"p cnf ",
capture(vars, range(0).to(Gecode.intMax)),
" ",
capture(clauses, atLeast(0)));
// The terminating 0 is not stored.
repeat(clauses, () -> list(clause, range(vars.neg()).to(vars).until(0)));
});
private BuildDimacsCnf() {}
public static void main(String[] args) {
Data data = spec.read(Path.of("formats/dimacs-cnf/cases/three-variables/input.txt"));
System.out.println(data.get(vars) + " variables");
for (long[] literals : data.get(clause)) {
System.out.println(Arrays.toString(literals));
}
}
}
3 variables
[1, -2]
[2, 3, -1]
[-3]
BuildSudoku.java
package examples;
import static dev.gecode.iris.build.Iris.*;
import dev.gecode.iris.Data;
import dev.gecode.iris.Spec;
import dev.gecode.iris.build.IntField;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
/** A Sudoku reader: the grid size, the box size, and the cells, with 0 for a blank. */
public final class BuildSudoku {
public static final IntField<Long> n = int0("n");
public static final IntField<Long> boxWidth = int0("box_width");
public static final IntField<Long> boxHeight = int0("box_height");
public static final IntField<List<long[]>> cells = int2("cells");
/** Cell values from 1 to 36, so {@code 1} reads as 1 and {@code 0} as 36. */
private static final String SYMBOLS = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0";
public static final Spec spec =
spec(
"sudoku",
() ->
instances(() -> {
line(
"# size=",
capture(n, atLeast(1)),
" box=",
capture(boxWidth, atLeast(1)),
"x",
capture(boxHeight, atLeast(1)));
read(cells, alphabet(SYMBOLS).blank(".").dim(n).dim(n));
check(boxWidth.times(boxHeight).eq(n), "boxes must tile the grid");
check(max(cells).le(n), "a value is larger than the size of the grid");
}));
private BuildSudoku() {}
public static void main(String[] args) {
Data data = spec.read(Path.of("formats/sudoku/cases/four-by-four/input.txt"));
long size = data.get(n);
System.out.printf(
"%dx%d grid with %dx%d boxes%n", size, size, data.get(boxWidth), data.get(boxHeight));
for (long[] row : data.get(cells)) {
System.out.println(Arrays.toString(row));
}
}
}
4x4 grid with 2x2 boxes
[1, 0, 0, 4]
[0, 4, 1, 0]
[0, 1, 4, 0]
[4, 0, 0, 1]

defineType gives a named type, used here for both ends of a time window:

BuildTsptw.java
package examples;
import static dev.gecode.iris.build.Iris.*;
import dev.gecode.iris.Data;
import dev.gecode.iris.Spec;
import dev.gecode.iris.build.Gecode;
import dev.gecode.iris.build.IntField;
import dev.gecode.iris.build.RecordName;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
/**
* 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.
*/
public final class BuildTsptw {
public static final IntField<Long> n = int0("n");
public static final IntField<List<long[]>> dist = int2("dist");
public static final IntField<long[]> ready = int1("ready");
public static final IntField<long[]> due = int1("due");
private static final RecordName node = recordName("node", "nodes");
public static final Spec spec =
spec(
"tsptw",
() -> {
comment("#");
read(n, range(2).to(1000));
read(dist, range(0).to(Gecode.intMax.div(2).div(n)).dim(n).dim(n));
var time = defineType("time", range(0).to(Gecode.intMax.div(2)));
repeat(
n,
node,
() -> {
read(ready, time);
read(due, time);
});
check(node.get(ready).le(node.get(due)), "the time window of a node is invalid");
check(node.list().at(0).get(ready).eq(0), "the depot (node 0) must open at time 0");
});
private BuildTsptw() {}
public static void main(String[] args) {
Data data = spec.read(Path.of("formats/tsptw/cases/three-nodes/input.txt"));
System.out.println(data.get(n) + " nodes");
List<long[]> distances = data.get(dist);
long[] opens = data.get(ready);
long[] closes = data.get(due);
for (int k = 0; k < distances.size(); k++) {
System.out.printf(
"node %d: open %d..%d, distances %s%n",
k, opens[k], closes[k], Arrays.toString(distances.get(k)));
}
}
}
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. set gives an optional entry a default while keeping its handle’s type, ifThen and otherwise take the checks that apply to each kind of file, and oneOf is an ordinary method that builds an expression:

BuildTsplib.java
package examples;
import static dev.gecode.iris.build.Iris.*;
import dev.gecode.iris.Data;
import dev.gecode.iris.Spec;
import dev.gecode.iris.build.FloatField;
import dev.gecode.iris.build.Gecode;
import dev.gecode.iris.build.IntExpr;
import dev.gecode.iris.build.IntField;
import dev.gecode.iris.build.RecordName;
import dev.gecode.iris.build.StringField;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import org.jspecify.annotations.Nullable;
/**
* A TSPLIB reader. A file gives either an explicit distance matrix or node coordinates, from which
* the distances follow.
*/
public final class BuildTsplib {
/** The entries of one section of numbered coordinates, whose names start with a prefix. */
public record Coordinates(
IntField<long @Nullable []> node,
FloatField<double @Nullable []> x,
FloatField<double @Nullable []> y) {
Coordinates(String prefix) {
this(
int1(prefix + "node").optional(),
float1(prefix + "x").optional(),
float1(prefix + "y").optional());
}
}
public static final StringField<@Nullable String> name = string0("name").optional();
public static final StringField<@Nullable String> type = string0("type").optional();
public static final IntField<Long> n = int0("n");
public static final StringField<@Nullable String> edgeWeightType =
string0("edge_weight_type").optional();
public static final StringField<@Nullable String> edgeWeightFormat =
string0("edge_weight_format").optional();
public static final StringField<@Nullable String> nodeCoordType =
string0("node_coord_type").optional();
public static final StringField<@Nullable String> displayDataType =
string0("display_data_type").optional();
public static final Coordinates coordinates = new Coordinates("");
public static final IntField<@Nullable List<long[]>> weight = int2("weight").optional();
public static final Coordinates display = new Coordinates("display_");
private static final RecordName nodes = recordName("_", "nodes");
public static final Spec spec =
spec(
"tsplib",
() -> {
comment("COMMENT");
sections(
until("EOF"),
() -> {
arm(pattern("NAME : ", capture(name, rest())), optional());
arm(pattern("TYPE : ", capture(type, word())), optional());
arm(pattern("DIMENSION : ", capture(n, range(2).to(46340))));
arm(pattern("EDGE_WEIGHT_TYPE : ", capture(edgeWeightType, word())), optional());
arm(
pattern("EDGE_WEIGHT_FORMAT : ", capture(edgeWeightFormat, word())),
optional());
arm(pattern("NODE_COORD_TYPE : ", capture(nodeCoordType, word())), optional());
arm(
pattern("DISPLAY_DATA_TYPE : ", capture(displayDataType, word())),
optional());
coordinateSection("NODE_COORD_SECTION", n, nodes, coordinates);
arm(
"EDGE_WEIGHT_SECTION",
optional(),
() -> {
ifThen(
defined(edgeWeightFormat).not(),
() -> set(edgeWeightFormat, "FULL_MATRIX"));
var bound = Gecode.intMax.div(n);
read(weight, range(0).to(bound).dim(n).dim(n).layout(edgeWeightFormat));
});
coordinateSection("DISPLAY_DATA_SECTION", n, recordName(), display);
});
ifThen(defined(edgeWeightType).not(), () -> set(edgeWeightType, "EXPLICIT"));
var x = coordinates.x();
var y = coordinates.y();
ifThen(
edgeWeightType.eq("EXPLICIT"),
() -> {
check(defined(weight), "no EDGE_WEIGHT_SECTION");
check(size(weight).eq(n), "edge weights do not match DIMENSION");
});
otherwise(() -> {
check(
oneOf(edgeWeightType, "EUC_2D", "CEIL_2D", "ATT", "GEO"),
"EDGE_WEIGHT_TYPE must be EXPLICIT, EUC_2D, CEIL_2D, ATT, or GEO");
check(defined(x), "no NODE_COORD_SECTION");
check(size(nodes.list()).eq(n), "coordinates do not match DIMENSION");
check(
x.ge(-1e9).and(x.le(1e9)).and(y.ge(-1e9)).and(y.le(1e9)),
"coordinates must be between -1e9 and 1e9");
});
});
private BuildTsplib() {}
/** Adds the optional section {@code title} of {@code n} lines {@code node x y}. */
static void coordinateSection(String title, IntField<Long> n, RecordName lines, Coordinates c) {
arm(
title,
optional(),
() ->
repeat(
n,
lines,
() -> {
read(c.node(), intType());
read(c.x(), floatType());
read(c.y(), floatType());
}));
}
/** Whether {@code entry} is one of {@code values}: {@code entry == "A" || entry == "B"}. */
static IntExpr oneOf(StringField<?> entry, String first, String... rest) {
IntExpr any = entry.eq(first);
for (String value : rest) {
any = any.or(entry.eq(value));
}
return any;
}
public static void main(String[] args) {
for (String example : List.of("explicit-five", "euc-2d-five")) {
Data data = spec.read(Path.of("formats/tsplib/cases/" + example + "/input.txt"));
String problem = data.get(name);
System.out.printf(
"%s: %d cities, %s%n",
problem == null ? "unnamed" : problem, data.get(n), data.get(edgeWeightType));
List<long[]> weights = data.get(weight);
if (weights != null) {
for (long[] row : weights) {
System.out.println(" " + Arrays.toString(row));
}
}
double[] x = data.get(coordinates.x());
double[] y = data.get(coordinates.y());
if (x != null && y != null) {
System.out.println(" x " + Arrays.toString(x));
System.out.println(" y " + Arrays.toString(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.0, 3.0, 3.0, 0.0, 1.5]
  y [0.0, 0.0, 4.0, 4.0, 2.0]

dev.gecode.iris.kotlin.build gives the builder Kotlin’s syntax: blocks are trailing lambdas, infix functions such as le and operators such as - and / build expressions, and a property delegate such as val nJobs by capture(atLeast(1), name = "n_jobs") defines an entry and its handle at once. irisSpec returns the spec with what its lambda returns, here a class of handles, and the pair destructures as val (spec, shop) = jobshop. data[shop.machine] calls the Java get as an operator, and the Java types become Kotlin’s: List<LongArray> for machine and String? for name. The Kotlin spec builder reference lists irisSpec, the statements of a scope and the capture delegates.

BuildJobshop.kt
package examples
import dev.gecode.iris.IrisException
import dev.gecode.iris.Params
import dev.gecode.iris.build.Gecode
import dev.gecode.iris.build.IntField
import dev.gecode.iris.build.StringField
import dev.gecode.iris.kotlin.build.IrisSpec
import dev.gecode.iris.kotlin.build.atLeast
import dev.gecode.iris.kotlin.build.distinct
import dev.gecode.iris.kotlin.build.irisSpec
import dev.gecode.iris.kotlin.build.le
import dev.gecode.iris.kotlin.build.range
import dev.gecode.iris.kotlin.build.recordName
import dev.gecode.iris.kotlin.build.sum
import dev.gecode.iris.kotlin.build.word
import java.nio.file.Files
import java.nio.file.Path
private const val TWICE = "a job uses a machine twice; each job must use every machine once"
/** The handles of a job shop instance, which the builder returns beside the spec. */
class Shop(
val name: StringField<String?>,
val nJobs: IntField<Long>,
val nMachines: IntField<Long>,
val machine: IntField<List<LongArray>>,
val duration: IntField<List<LongArray>>,
)
/**
* 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.
*/
val jobshop: IrisSpec<Shop> =
irisSpec("jobshop") {
comment("#", "+++")
instances {
val name by optionalCapture(word())
val nJobs by capture(atLeast(1), name = "n_jobs")
val nMachines by capture(atLeast(1), name = "n_machines")
// Error messages name the records of the jobs.
val jobs = recordName("job", "jobs")
val (machine, duration) =
sections(skipOther = true) {
arm("instance ", name, optional = true)
arm(nJobs, " ", nMachines, last = true) {
check(
nJobs le (Gecode.intMax - 2) / 2 / nMachines,
"there are too many jobs and machines",
)
repeat(nJobs, jobs) {
repeat(nMachines) {
read("machine", range(0).below(nMachines)) to
read("duration", atLeast(0))
}
}
}
}
check(distinct(jobs[machine]), TWICE)
check(
sum(jobs) { sum(it[duration]) } le Gecode.intMax,
"the total duration is too large",
)
Shop(name, nJobs, nMachines, machine, duration)
}
}
fun main() {
val (spec, shop) = jobshop
val orLibrary = Path.of("formats/jobshop/cases/or-library/input.txt")
val data = spec.read(orLibrary, Params.of("instance", "handmade-or"))
println(
"${data[shop.name] ?: "unnamed"}: ${data[shop.nJobs]} jobs on " +
"${data[shop.nMachines]} machines"
)
val durations = data[shop.duration]
for ((j, machines) in data[shop.machine].withIndex()) {
println(
"job $j: machines ${machines.contentToString()}, " +
"durations ${durations[j].contentToString()}"
)
}
// Errors name a path's input with the platform's separators, so this read
// names the input itself to print the same on every platform.
val invalid = "formats/jobshop/cases/duplicate-machine/input.txt"
try {
spec.read(
Files.readAllBytes(Path.of(invalid)),
invalid,
Params.of("instance", "handmade-invalid"),
)
} catch (error: IrisException) {
println()
println("${error.code().code()} at ${error.origin()}:${error.line()}:${error.column()}")
println(error.error().message())
// The statement's call site: the line of the distinct check above.
val site = error.callSite().orElseThrow()
println("call site: ${site.fileName}:${site.lineNumber}")
}
}
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: BuildJobshop.kt:60
BuildNonogram.kt
package examples
import dev.gecode.iris.build.IntExpr
import dev.gecode.iris.build.IntField
import dev.gecode.iris.build.RecordName
import dev.gecode.iris.kotlin.build.IrisSpec
import dev.gecode.iris.kotlin.build.Scope0
import dev.gecode.iris.kotlin.build.and
import dev.gecode.iris.kotlin.build.atLeast
import dev.gecode.iris.kotlin.build.count
import dev.gecode.iris.kotlin.build.eq
import dev.gecode.iris.kotlin.build.gt
import dev.gecode.iris.kotlin.build.int2
import dev.gecode.iris.kotlin.build.irisSpec
import dev.gecode.iris.kotlin.build.le
import dev.gecode.iris.kotlin.build.lit
import dev.gecode.iris.kotlin.build.min
import dev.gecode.iris.kotlin.build.or
import dev.gecode.iris.kotlin.build.size
import dev.gecode.iris.kotlin.build.sum
import java.nio.file.Path
private const val MAX_FIELDS = 1_000_000L
/** The handles of a nonogram: the board size and the clues of each row and column. */
class Board(
val width: IntField<Long>,
val height: IntField<Long>,
val row: IntField<List<LongArray>>,
val col: IntField<List<LongArray>>,
)
/** A nonogram reader: the board size and the clues of each row and column. */
val nonogram: IrisSpec<Board> =
irisSpec("nonogram") {
separators(",")
val width by capture(atLeast(1))
val height by capture(atLeast(1))
val row = int2("row")
val col = int2("col")
val (rows, cols) =
sections(skipOther = true) {
arm("width ", width)
arm("height ", height)
val rows = arm("rows") { clueLines(height, row) }
val cols = arm("columns") { clueLines(width, col) }
rows to cols
}
check(height le lit(MAX_FIELDS) / width, "the board must have at most a million fields")
check(
(size(rows.list()) eq height) and (size(cols.list()) eq width),
"the numbers of rows and columns differ from the board size",
)
check(zeroStandsAlone(row), "a 0 must be the only clue of its row")
check(zeroStandsAlone(col), "a 0 must be the only clue of its column")
check(cluesFit(row, width), "the clues of a row do not fit into the width of the board")
check(
cluesFit(col, height),
"the clues of a column do not fit into the height of the board",
)
Board(width, height, row, col)
}
/** Reads [count] lines of comma-separated clues into [clues], and returns their records. */
private fun Scope0.clueLines(count: IntField<Long>, clues: IntField<List<LongArray>>): RecordName =
repeat(count) {
list(clues, atLeast(0).untilEol())
record
}
/** A 0 clue says the line is empty, so it must stand alone. */
private fun zeroStandsAlone(clues: IntField<List<LongArray>>): IntExpr =
(count(clues) le 1) or (min(clues) gt 0)
/** The clues and one gap between each pair of them fit into [length]. */
private fun cluesFit(clues: IntField<List<LongArray>>, length: IntField<Long>): IntExpr =
sum(clues) + count(clues) - 1 le length
fun main() {
val (spec, board) = nonogram
val data = spec.read(Path.of("formats/nonogram/cases/five-by-five/input.txt"))
println("${data[board.width]}x${data[board.height]} board")
println("rows: ${clues(data[board.row])}")
println("columns: ${clues(data[board.col])}")
}
/** [lines] as `[[1, 2], [3]]`. */
private fun clues(lines: List<LongArray>): String =
lines.joinToString(", ", "[", "]") { it.contentToString() }
5x5 board
rows: [[1, 1], [1, 1], [1], [1, 1], [1, 1]]
columns: [[1, 1], [1, 1], [1], [1, 1], [1, 1]]
BuildDimacsCnf.kt
package examples
import dev.gecode.iris.build.Gecode
import dev.gecode.iris.build.IntField
import dev.gecode.iris.kotlin.build.IrisSpec
import dev.gecode.iris.kotlin.build.atLeast
import dev.gecode.iris.kotlin.build.int2
import dev.gecode.iris.kotlin.build.irisSpec
import dev.gecode.iris.kotlin.build.rangeTo
import dev.gecode.iris.kotlin.build.unaryMinus
import java.nio.file.Path
/** The literal that ends a clause. */
private const val END_OF_CLAUSE = 0L
/** The handles of a CNF formula. */
class Cnf(
val vars: IntField<Long>,
val clauses: IntField<Long>,
val clause: IntField<List<LongArray>>,
)
/** A DIMACS CNF reader: the number of variables and one row of literals per clause. */
val dimacsCnf: IrisSpec<Cnf> =
irisSpec("dimacs-cnf") {
comment("c")
stop("%") // SATLIB files end with "%" and "0"
val vars by capture(0..Gecode.intMax)
val clauses by capture(atLeast(0))
line("p cnf ", vars, " ", clauses)
val clause = int2("clause")
// The terminating 0 is not stored.
repeat(clauses) { list(clause, (-vars..vars).until(END_OF_CLAUSE)) }
Cnf(vars, clauses, clause)
}
fun main() {
val (spec, cnf) = dimacsCnf
val data = spec.read(Path.of("formats/dimacs-cnf/cases/three-variables/input.txt"))
println("${data[cnf.vars]} variables")
for (literals in data[cnf.clause]) {
println(literals.contentToString())
}
}
3 variables
[1, -2]
[2, 3, -1]
[-3]
BuildSudoku.kt
package examples
import dev.gecode.iris.build.IntField
import dev.gecode.iris.kotlin.build.IrisSpec
import dev.gecode.iris.kotlin.build.alphabet
import dev.gecode.iris.kotlin.build.atLeast
import dev.gecode.iris.kotlin.build.eq
import dev.gecode.iris.kotlin.build.int2
import dev.gecode.iris.kotlin.build.irisSpec
import dev.gecode.iris.kotlin.build.le
import dev.gecode.iris.kotlin.build.max
import java.nio.file.Path
/** Cell values from 1 to 36, so `1` reads as 1 and `0` as 36. */
private const val SYMBOLS = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0"
/** The handles of a Sudoku: the grid size, the box size, and the cells, with 0 for a blank. */
class Grid(
val n: IntField<Long>,
val boxWidth: IntField<Long>,
val boxHeight: IntField<Long>,
val cells: IntField<List<LongArray>>,
)
/** A Sudoku reader: the grid size, the box size, and the cells, with 0 for a blank. */
val sudoku: IrisSpec<Grid> =
irisSpec("sudoku") {
instances {
val n by capture(atLeast(1))
val boxWidth by capture(atLeast(1), name = "box_width")
val boxHeight by capture(atLeast(1), name = "box_height")
line("# size=", n, " box=", boxWidth, "x", boxHeight)
val cells = int2("cells")
read(cells, alphabet(SYMBOLS).blank(".").dim(n).dim(n))
check(boxWidth * boxHeight eq n, "boxes must tile the grid")
check(max(cells) le n, "a value is larger than the size of the grid")
Grid(n, boxWidth, boxHeight, cells)
}
}
fun main() {
val (spec, grid) = sudoku
val data = spec.read(Path.of("formats/sudoku/cases/four-by-four/input.txt"))
val size = data[grid.n]
println("${size}x$size grid with ${data[grid.boxWidth]}x${data[grid.boxHeight]} boxes")
for (row in data[grid.cells]) {
println(row.contentToString())
}
}
4x4 grid with 2x2 boxes
[1, 0, 0, 4]
[0, 4, 1, 0]
[0, 1, 4, 0]
[4, 0, 0, 1]
BuildTsptw.kt
package examples
import dev.gecode.iris.build.Gecode
import dev.gecode.iris.build.IntField
import dev.gecode.iris.kotlin.build.IrisSpec
import dev.gecode.iris.kotlin.build.eq
import dev.gecode.iris.kotlin.build.int2
import dev.gecode.iris.kotlin.build.irisSpec
import dev.gecode.iris.kotlin.build.le
import dev.gecode.iris.kotlin.build.range
import dev.gecode.iris.kotlin.build.recordName
import java.nio.file.Path
private const val MAX_NODES = 1000L
/** The handles of a time-window problem: distances and a time window for each node. */
class TimeWindows(
val n: IntField<Long>,
val dist: IntField<List<LongArray>>,
val ready: IntField<LongArray>,
val due: IntField<LongArray>,
)
/**
* 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.
*/
val tsptw: IrisSpec<TimeWindows> =
irisSpec("tsptw") {
comment("#")
val n = read("n", range(2).to(MAX_NODES))
val dist = int2("dist")
read(dist, range(0).to(Gecode.intMax / 2 / n).dim(n).dim(n))
val time = defineType("time", range(0).to(Gecode.intMax / 2))
val nodes = recordName("node", "nodes")
val (ready, due) = repeat(n, nodes) { read("ready", time) to read("due", time) }
check(nodes[ready] le nodes[due], "the time window of a node is invalid")
check(nodes.list().at(0)[ready] eq 0, "the depot (node 0) must open at time 0")
TimeWindows(n, dist, ready, due)
}
fun main() {
val (spec, windows) = tsptw
val data = spec.read(Path.of("formats/tsptw/cases/three-nodes/input.txt"))
println("${data[windows.n]} nodes")
val opens = data[windows.ready]
val closes = data[windows.due]
for ((k, distances) in data[windows.dist].withIndex()) {
println("node $k: open ${opens[k]}..${closes[k]}, distances ${distances.contentToString()}")
}
}
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]
BuildTsplib.kt
package examples
import dev.gecode.iris.build.FloatField
import dev.gecode.iris.build.Gecode
import dev.gecode.iris.build.IntExpr
import dev.gecode.iris.build.IntField
import dev.gecode.iris.build.RecordName
import dev.gecode.iris.build.StringField
import dev.gecode.iris.build.TextualExpr
import dev.gecode.iris.kotlin.build.IrisSpec
import dev.gecode.iris.kotlin.build.OptionalScope0
import dev.gecode.iris.kotlin.build.Scope0
import dev.gecode.iris.kotlin.build.Sections
import dev.gecode.iris.kotlin.build.and
import dev.gecode.iris.kotlin.build.defined
import dev.gecode.iris.kotlin.build.eq
import dev.gecode.iris.kotlin.build.float
import dev.gecode.iris.kotlin.build.ge
import dev.gecode.iris.kotlin.build.int
import dev.gecode.iris.kotlin.build.int2
import dev.gecode.iris.kotlin.build.irisSpec
import dev.gecode.iris.kotlin.build.le
import dev.gecode.iris.kotlin.build.or
import dev.gecode.iris.kotlin.build.range
import dev.gecode.iris.kotlin.build.recordName
import dev.gecode.iris.kotlin.build.rest
import dev.gecode.iris.kotlin.build.size
import dev.gecode.iris.kotlin.build.until
import dev.gecode.iris.kotlin.build.word
import java.nio.file.Path
private const val MAX_DIMENSION = 46_340L
private const val COORDINATE_BOUND = 1e9
/** The handles of one section of numbered coordinates. */
class Coordinates(
val node: IntField<LongArray?>,
val x: FloatField<DoubleArray?>,
val y: FloatField<DoubleArray?>,
)
/** The handles of a TSPLIB file. */
class Tsp(
val name: StringField<String?>,
val n: IntField<Long>,
val edgeWeightType: StringField<String?>,
val coordinates: Coordinates,
val weight: IntField<List<LongArray>?>,
val display: Coordinates,
)
/**
* A TSPLIB reader. A file gives either an explicit distance matrix or node coordinates, from which
* the distances follow.
*/
val tsplib: IrisSpec<Tsp> =
irisSpec("tsplib") {
comment("COMMENT")
val name by optionalCapture(rest())
val type by optionalCapture(word())
val n by capture(range(2).to(MAX_DIMENSION))
val edgeWeightType by optionalCapture(word(), name = "edge_weight_type")
val edgeWeightFormat by optionalCapture(word(), name = "edge_weight_format")
val nodeCoordType by optionalCapture(word(), name = "node_coord_type")
val displayDataType by optionalCapture(word(), name = "display_data_type")
val weight = int2("weight").optional()
val nodes = recordName("_", "nodes")
val (coordinates, display) =
sections(until("EOF")) {
arm("NAME : ", name, optional = true)
arm("TYPE : ", type, optional = true)
arm("DIMENSION : ", n)
arm("EDGE_WEIGHT_TYPE : ", edgeWeightType, optional = true)
arm("EDGE_WEIGHT_FORMAT : ", edgeWeightFormat, optional = true)
arm("NODE_COORD_TYPE : ", nodeCoordType, optional = true)
arm("DISPLAY_DATA_TYPE : ", displayDataType, optional = true)
val coordinates = coordinateSection("NODE_COORD_SECTION", n, "", nodes)
optionalArm("EDGE_WEIGHT_SECTION") {
ifThen(!defined(edgeWeightFormat)) { set(edgeWeightFormat, "FULL_MATRIX") }
val bound = Gecode.intMax / n
read(weight, range(0).to(bound).dim(n).dim(n).layout(edgeWeightFormat))
}
val display = coordinateSection("DISPLAY_DATA_SECTION", n, "display_")
coordinates to display
}
ifThen(!defined(edgeWeightType)) { set(edgeWeightType, "EXPLICIT") }
val (x, y) = coordinates.x to coordinates.y
ifThen(edgeWeightType eq "EXPLICIT") {
check(defined(weight), "no EDGE_WEIGHT_SECTION")
check(size(weight) eq n, "edge weights do not match DIMENSION")
}
otherwise {
check(
edgeWeightType.oneOf("EUC_2D", "CEIL_2D", "ATT", "GEO"),
"EDGE_WEIGHT_TYPE must be EXPLICIT, EUC_2D, CEIL_2D, ATT, or GEO",
)
check(defined(x), "no NODE_COORD_SECTION")
check(size(nodes.list()) eq n, "coordinates do not match DIMENSION")
check(
(x ge -COORDINATE_BOUND) and
(x le COORDINATE_BOUND) and
(y ge -COORDINATE_BOUND) and
(y le COORDINATE_BOUND),
"coordinates must be between -1e9 and 1e9",
)
}
Tsp(name, n, edgeWeightType, coordinates, weight, display)
}
/** Adds the optional section [title] of [n] lines `node x y`, with entry names after [prefix]. */
private fun Sections<Scope0, OptionalScope0>.coordinateSection(
title: String,
n: IntField<Long>,
prefix: String,
lines: RecordName = recordName(),
): Coordinates =
optionalArm(title) {
repeat(n, lines) {
Coordinates(
read("${prefix}node", int()),
read("${prefix}x", float()),
read("${prefix}y", float()),
)
}
}
/** Whether this is one of [values]: `this == "A" || this == "B"`. */
private fun TextualExpr.oneOf(vararg values: String): IntExpr =
values.map { this eq it }.reduce { any, next -> any or next }
fun main() {
val (spec, tsp) = tsplib
for (example in listOf("explicit-five", "euc-2d-five")) {
val data = spec.read(Path.of("formats/tsplib/cases/$example/input.txt"))
println(
"${data[tsp.name] ?: "unnamed"}: ${data[tsp.n]} cities, ${data[tsp.edgeWeightType]}"
)
data[tsp.weight]?.forEach { println(" ${it.contentToString()}") }
val x = data[tsp.coordinates.x]
val y = data[tsp.coordinates.y]
if (x != null && y != null) {
println(" x ${x.contentToString()}")
println(" y ${y.contentToString()}")
}
}
}
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]

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

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

import static dev.gecode.iris.build.Iris.*;

import dev.gecode.iris.build.IntField;
import dev.gecode.iris.build.StringField;
import java.util.List;
import org.jspecify.annotations.Nullable;

public final class Jobshop {
  public static final StringField<java.lang.@Nullable String> name = string0("name").optional();
  public static final IntField<java.lang.Long> nJobs = int0("n_jobs");
  public static final IntField<java.lang.Long> nMachines = int0("n_machines");
  public static final IntField<List<long[]>> machine = int2("machine");
  public static final IntField<List<long[]>> duration = int2("duration");

  private Jobshop() {}
}

Save it in your package, such as Jobshop.java with a package line after the first comment, 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 a DynField, which returns a Value, and an entry deeper than three levels returns a Value too. The class qualifies the types of java.lang, such as java.lang.Long, so that a class named Long or String in your package cannot take their place. iris gen --lang kotlin SPEC prints an object of the same handles for Kotlin, which imports the standard library’s types for the same reason:

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

import dev.gecode.iris.build.IntField
import dev.gecode.iris.build.StringField
import dev.gecode.iris.kotlin.build.int0
import dev.gecode.iris.kotlin.build.int2
import dev.gecode.iris.kotlin.build.string0
import kotlin.Long
import kotlin.LongArray
import kotlin.String
import kotlin.collections.List

public object Jobshop {
    public val name: StringField<String?> = string0("name").optional()
    public val nJobs: IntField<Long> = int0("n_jobs")
    public val nMachines: IntField<Long> = int0("n_machines")
    public val machine: IntField<List<LongArray>> = int2("machine")
    public val duration: IntField<List<LongArray>> = int2("duration")
}

The annotation processor dev.gecode:iris-processor writes the same handles while javac compiles, so they follow the .iris file without a step of their own. It is needed only to compile:

build.gradle.kts
dependencies {
compileOnly("dev.gecode:iris-processor:0.1.0")
annotationProcessor("dev.gecode:iris-processor:0.1.0")
}
tasks.compileJava {
options.compilerArgs.add("-Airis.root=${projectDir}")
inputs.dir("specs")
}

-Airis.root names the directory that relative paths start from; without it, a path starts at the directory of the annotated source file. Declaring the specs as inputs, here a directory specs, recompiles when one changes. The processor leaves the annotation unclaimed, so a build with -Xlint:all -Werror adds -Xlint:-processing. In Maven, the processor goes in the compiler plugin’s annotationProcessorPaths.

On a top-level type annotated with @IrisSpec, the processor checks the spec and writes two classes beside the type: JobshopHandles, with the parsed spec as spec, the handles that iris gen --lang java prints, and a record reader as reader, and JobshopData, the record that reader reads. An invalid spec fails the compilation with the diagnostic at the annotation. A spec whose entries take more than 254 parameter slots in a record, where a long or double component takes two, gets the handles but no record or reader, since a constructor takes at most 254; the processor notes it. The generated classes are laid out as google-java-format lays them out.

Jobshop.java
package examples;
import dev.gecode.iris.Data;
import dev.gecode.iris.Params;
import dev.gecode.iris.processor.IrisSpec;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
/** The job shop reader spec, whose handles and record iris-processor writes when this compiles. */
@IrisSpec("formats/jobshop/jobshop.iris")
public final class Jobshop {
private Jobshop() {}
public static void main(String[] args) {
Path orLibrary = Path.of("formats/jobshop/cases/or-library/input.txt");
Data data = JobshopHandles.spec.read(orLibrary, Params.of("instance", "handmade-or"));
List<long[]> machines = data.get(JobshopHandles.machine);
System.out.printf(
"%s: %d jobs, the first on machines %s%n",
data.get(JobshopHandles.name),
data.get(JobshopHandles.nJobs),
Arrays.toString(machines.get(0)));
Path jsplib = Path.of("formats/jobshop/cases/jsplib/input.txt");
JobshopData shop = JobshopHandles.reader.read(jsplib);
System.out.printf(
"%d jobs on %d machines, the first with durations %s%n",
shop.nJobs(), shop.nMachines(), Arrays.toString(shop.duration().get(0)));
}
}
handmade-or: 3 jobs, the first on machines [0, 1, 2]
3 jobs on 3 machines, the first with durations [3, 2, 4]

The processor’s reference lists the annotation and its options. The processor runs in javac, so Kotlin code uses the handles of an annotated Java type, or the object that iris gen --lang kotlin prints.