Introduction
RedSAT (Reduce → SAT) is a programming language whose programs are solved, not executed. You declare variables, state what must be true of them, and say which values you want to see. RedSAT works out the values for you.
Here is a whole program. It finds the two factors of a number:
var n = 4295229443 // known: we picked this number
var x, y // unknowns: RedSAT finds them
require x > 1 and y > 1 // rule out the boring answer 1 × n
require x <= y // list each pair of factors once
require x * y == n
solve x, y {
print "{n} = {x} × {y}"
}
4295229443 = 65537 × 65539
It reads like ordinary code, but nothing in it says how to find x and y: there is no loop
over candidates, no clever algorithm. The program only describes what an answer looks like, and
the solve statement asks for one.
How it works, in a nutshell
- RedSAT reads your program and runs everything it can run right away:
nis simply a number. - Everything that depends on the unknowns
xandybecomes a Boolean circuit. The multiplicationx * yturns into a multiplier circuit, much like the one inside a CPU. - That circuit, together with the requirements, is turned into a SAT problem: a big formula over true/false variables. This reduction always takes polynomial time.
- A state-of-the-art SAT solver finds values for those true/false variables, which is like
running the multiplier backwards: which inputs make it output
n? - RedSAT decodes the solver’s answer back into your program’s values, here two integers, and
runs the body of
solvewith them.
A few things make this pleasant to use:
- Integers are exact. There is no overflow, ever. RedSAT works out how many bits every
value needs from your constraints, so
x * yalways gets enough bits for its true value. - Types are inferred.
var x, yis enough: using them inx * y == nmakes them integers, and the requirements bound them. - It is a real language. There are functions, loops,
if, arrays, strings, enums, structs, a standard library and imports. Code that runs on known values works on unknowns too.
What is it good for?
Anything you can describe more easily than you can compute: puzzles (Sudoku, cryptarithms, logic riddles), scheduling and timetabling, packing and selection problems, configuration, colouring and assignment problems, or “running a function backwards” to find an input that produces a given output. The Cookbook walks through many of these.
These problems are typically NP-hard: no known method solves every instance quickly. SAT solvers are remarkably good at the instances people actually meet, but they are not magic. The Performance tips explain how to help them.
How to read this guide
- Getting started installs RedSAT and runs your first programs.
- Learn RedSAT is a tutorial, one concept per chapter. Read it in order.
- Cookbook shows how to model classic problems, starting each one in plain language.
- Reference is the place to look things up: syntax, types, operators, every built-in and standard library function, the command line and the configuration file.
- Under the hood explains how programs become SAT problems, and how to make them fast.
Every RedSAT program in this guide is tested against the compiler, and the output shown below each one is exactly what it prints.
Want to try RedSAT without installing anything? Open the online playground.
Getting started
This part gets RedSAT onto your machine and walks you through your first programs:
- Installation: build the
redsatcommand from source. - Your first program: a small puzzle, line by line.
- Running programs: the everyday commands, from running a program to seeing what the solver did.
- The REPL: build a program one statement at a time.
- Editor support: the VS Code extension, with highlighting, live errors and the inferred range of every unknown on hover.
Just curious? The online playground runs RedSAT programs in your browser, with nothing to install.
Installation
RedSAT is written in Rust and builds into a single command-line program, redsat.
Prerequisites
-
Rust, version 1.85 or newer. If you do not have it yet, install it with rustup:
$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -
A C++ compiler and libclang. RedSAT bundles the CaDiCaL SAT solver, which is written in C++ and compiled as part of the build. On Debian or Ubuntu:
$ sudo apt install build-essential libclang-dev
Build and install
From a checkout of the RedSAT repository:
$ cargo install --path crates/redsat-cli
This compiles RedSAT in release mode and puts redsat into ~/.cargo/bin, which rustup adds
to your PATH. Check that it works:
$ redsat --version
redsat 0.1.0
To update RedSAT later, pull the latest sources and run the same cargo install command again.
Running without installing
Inside the repository you can also run RedSAT through Cargo, without installing it:
$ cargo run --release -p redsat-cli -- examples/factor.rsat
4295229443 = 65537 × 65539
Everything after -- is passed to redsat. Use --release: an unoptimised build is much
slower at solving.
Running the tests
If you are working on RedSAT itself, the whole test suite runs with:
$ cargo test --workspace
It includes the examples in examples/ and every code sample in this guide.
Next steps
- Write your first program.
- Install the VS Code extension for highlighting and live feedback.
Your first program
Let’s solve a puzzle that has been around for over 1,500 years:
A farmer counts 35 heads and 94 legs among the chickens and rabbits in the yard. How many chickens and how many rabbits are there?
You could solve this with a bit of algebra. In RedSAT you don’t have to: you write down what you know, and ask for the rest.
The program
Save this program as farm.rsat and run it with redsat farm.rsat:
var heads = 35
var legs = 94
var chickens, rabbits
require chickens >= 0 and rabbits >= 0
require chickens + rabbits == heads
require 2 * chickens + 4 * rabbits == legs
solve chickens, rabbits
chickens = 23, rabbits = 12
That’s the answer: 23 chickens and 12 rabbits.
Line by line
var heads = 35 and var legs = 94: var declares a variable. These two have values,
so they are known: plain numbers, just as in any other language.
var chickens, rabbits: these two have no value, so they are unknowns. Finding their
values is the whole point of the program. Notice that there is no type: RedSAT sees them used
in arithmetic below and makes them integers.
require …: each require states something that must be true of the answer. A chicken has
one head and two legs, a rabbit one head and four legs. We also say that the counts can’t be
negative: RedSAT’s integers are real mathematical integers, so without that line -1 rabbits
would be fair game.
solve chickens, rabbits: solve asks RedSAT to find values for the unknowns that satisfy
every requirement, and to show the ones listed after it. Without a body, it prints them as
name = value.
Make it yours
Programs are short, so experimenting is cheap. Try these changes one at a time.
Print the answer your way. A solve can have a body. It runs once the unknowns have their
values, so inside it they are ordinary numbers:
var heads = 35
var legs = 94
var chickens, rabbits
require chickens >= 0 and rabbits >= 0
require chickens + rabbits == heads
require 2 * chickens + 4 * rabbits == legs
solve chickens, rabbits {
print "{chickens} chickens and {rabbits} rabbits"
print "check: {2 * chickens + 4 * rabbits} legs"
}
23 chickens and 12 rabbits
check: 94 legs
The {…} inside a string inserts the value of any expression.
Make sure the answer is the only one. solve unique finds a solution and then proves
that there is no other:
var heads = 35
var legs = 94
var chickens, rabbits
require chickens >= 0 and rabbits >= 0
require chickens + rabbits == heads
require 2 * chickens + 4 * rabbits == legs
solve unique chickens, rabbits
chickens = 23, rabbits = 12
If there were two answers, RedSAT would stop with an error showing both.
Ask for the impossible. Change the number of legs to 95 and run it again:
var heads = 35
var legs = 95
var chickens, rabbits
require chickens >= 0 and rabbits >= 0
require chickens + rabbits == heads
require 2 * chickens + 4 * rabbits == legs
solve chickens, rabbits
no solution
note: no solution: this requirement can never hold
--> main.rsat:7:9
|
7 | require 2 * chickens + 4 * rabbits == legs
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RedSAT doesn’t just say “no”: it points at the requirement responsible. Every animal has an even number of legs, so the total can never be odd.
What just happened?
When you ran the program, RedSAT:
- computed everything it could right away (
headsandlegs); - worked out from the requirements that
chickensandrabbitslie between 0 and 35, so each fits in a handful of bits; - turned the requirements into a SAT problem, a formula over true/false variables;
- handed it to the CaDiCaL SAT solver, and turned the solver’s answer back into two integers.
Run redsat farm.rsat --stats to see some of this: the inferred ranges of the unknowns, their
size in bits, and how big the SAT problem was. In this tiny puzzle RedSAT narrows both ranges
down to a single value before the solver even starts.
Next, learn the everyday commands in Running programs, or dive into the language with Knowns and unknowns.
Running programs
RedSAT programs live in .rsat files. This page covers the commands you will use every day;
the command-line reference lists every option.
Run a program
Running is the default action, so there is no run subcommand:
$ redsat examples/pythagorean.rsat
What the program prints goes to standard output. Errors, warnings and notes go to standard
error, after the program’s output. redsat exits with status 0 when the program ran without
errors and 1 otherwise. A solve that finds no solution is not an error: the program simply
prints no solution (or runs its else block) and carries on.
Check a program without running it
$ redsat check examples/coins.rsat
examples/coins.rsat: ok
check parses and type-checks the program, and stops there. It is quick, so it suits editors
and CI. Some mistakes only show up when the program runs, such as an array index that is out of
range: check does not find those, but a run (and the editor) does.
See what the solver worked with: --stats
$ redsat examples/factor.rsat --stats
4295229443 = 65537 × 65539
stats: solve at examples/factor.rsat:14
x: [34, 130158467] · 27 bits
y: [34, 130158467] · 27 bits
circuit: 5948 AND gates · CNF: 5832 variables, 16880 clauses
1 SAT call · 1 solution · 78.67ms (build 18.12ms, search 60.39ms)
For every solve, --stats shows each unknown’s inferred range and how many bits it
needed, the size of the circuit and of the SAT problem, how many times the solver was called,
and where the time went: build (inferring ranges, building the circuit) versus search (the
SAT solver).
Watch it happen: --verbose
-v / --verbose reports progress as it happens: which files were loaded, what each solve
is about to do, how large the search space is, and how long each step took.
$ redsat examples/coins.rsat --verbose
[redsat] loaded 2 files (examples/coins.rsat, <prelude>) · parsed and checked in 1.48ms
[redsat] solve #1 at examples/coins.rsat:12
[redsat] model first, minimize · 2 requirements · 28 IR terms
[redsat] unknowns 4 (4 integer, 0 boolean), 0 fixed by domain inference · domains in 42.48µs
[redsat] quarters: [0, 11] · 4 bits
[redsat] dimes: [0, 28] · 5 bits
[redsat] nickels: [0, 57] · 6 bits
[redsat] pennies: [0, 289] · 9 bits
[redsat] space 24 decision bits → 2^24 candidate assignments
[redsat] circuit 414 AND gates over 24 inputs → CNF 291 variables (267 auxiliary), 788 clauses · built in 4.33ms
[redsat] search with CaDiCaL…
289¢ = 11 quarters + 1 dimes + 0 nickels + 4 pennies (16 coins)
[redsat] searched 6 SAT calls · 1 solution · 13.31ms (CNF grew to 460 variables, 1305 clauses)
[redsat] finished in 19.55ms: 43 statements executed, no calls inlined, 1 solve taking 17.78ms
Reach for it when a program is slow: it tells you whether the time goes into building the
problem or into solving it, and how big the problem is. Each solve also gets a cost table
that breaks the size down by source line, like a database’s EXPLAIN ANALYZE, so you can see
which statements make the problem big. The
command-line reference explains every line.
Step through solutions: --interactive
$ redsat examples/pythagorean.rsat --interactive
18² + 24² = 30²
── 1 shown · [Enter] next · [a] all · [q] quit ──
After each solution, RedSAT waits: press Enter for the next one, a to show all the
remaining ones, or q to stop enumerating and let the program continue. This works for every
solve, even one that would normally stop after the first solution.
Choose the SAT solver: --solver
RedSAT uses CaDiCaL, a fast, award-winning SAT solver,
by default. --solver builtin switches to RedSAT’s own solver, written in pure Rust. It gives
the same answers, more slowly, and is mostly of interest for learning and testing.
Compiler options
Options such as --strict change what the compiler accepts. They can also live in a
redsat.toml file next to your programs: see Configuration.
The REPL
redsat repl starts an interactive session. Each statement you type is added to a program, and
RedSAT shows you what it prints. It is a handy way to try out an operator, a standard library
function, or a model you are still shaping.
$ redsat repl
RedSAT 0.1.0 — type :help for help, :quit to leave
rsat> var x, y: int[0..=9]
rsat> require x + y == 10
rsat> require x > y
rsat> solve all x, y
x = 9, y = 1
x = 6, y = 4
x = 7, y = 3
x = 8, y = 2
rsat> 2 ^ 100
1267650600228229401496703205376
rsat> sorted([3, 1, 2])
[1, 2, 3]
rsat> :quit
A few things to know:
- A bare expression is printed, as if you had written
printin front of it. That includes a function call on its own line, likesorted([3, 1, 2]), when the function returns a value; a function that returns nothing is just run. - Blocks can span several lines. Input continues (with a
...prompt) while a bracket is open, so you can type asolvebody, anifor a function over several lines. - Mistakes are not kept. An input with an error is reported and dropped; the program stays as it was.
- Constraints accumulate, exactly as in a file: each
solvesees everyrequireyou have entered so far. Use:undoto take back the last input, or:resetto start over.
Behind the scenes, the REPL runs the whole program again for each input and shows only the new output. Runs are deterministic, so earlier output never changes.
Commands
| Command | What it does |
|---|---|
:help | show the commands |
:show | print the program entered so far |
:undo | remove the last accepted input |
:reset | start over with an empty program |
:load <file> | append a file’s contents to the program |
:quit | leave the REPL (Ctrl-D works too) |
redsat repl accepts the same compiler options and --solver choice as running a file. It
looks for a redsat.toml in the current directory and its
parents.
Editor support
RedSAT comes with an extension for Visual Studio Code, in
editors/vscode/ of the repository. It has two layers:
- Highlighting, snippets and editing support, which work everywhere with nothing else installed.
- A language server, built into the
redsatcommand (redsat lsp), which adds live error checking, completion, hovers and more.
What you get
- Syntax highlighting for
.rsatfiles, including{…}interpolation inside strings, and for```rsatcode blocks in Markdown files. - Live diagnostics: syntax, type and strict-mode errors as you type, plus errors that only
show up when the program is elaborated, such as an index out of range or a loop bound that
depends on unknowns. A
redsat.tomlnext to the file is honoured. - Hovers that show inferred ranges. Hover over an unknown to see the range RedSAT inferred
for it and how many bits it needs, for example
unknown · inferred domain [34, 130158467] · 27 bits. The same information appears as inlay hints next to every unknown’s declaration. This is the quickest way to spot an unknown that is wider than you expected. - Autocomplete for variables, functions, enums, structs and built-ins; types after
:; enum variants afterColor.; struct fields afterp.; andsolvemodifiers. - Go to definition and a document outline.
- Snippets for common shapes: type
solveall,for,fn, … and press Tab.
The language server analyses your program exactly as a run would, but stops each solve before
calling the SAT solver, so the editor stays responsive. It also gives up quietly after a short
time on programs that take long to elaborate.
Installing
-
Install the
redsatcommand (see Installation). The extension starts it asredsat lsp. -
Build the extension (this needs Node.js 22 or newer):
$ cd editors/vscode $ npm install $ npm run package -
Install the resulting package and reload VS Code:
$ code --install-extension redsat-0.2.0.vsix --force
If the extension cannot find redsat, highlighting and snippets keep working, and the status
bar item next to RedSAT tells you why the language server did not start.
Windows and WSL
If you use VS Code on Windows with RedSAT installed inside WSL, open your project in a WSL
remote window and install the extension there too: it then runs next to the Linux redsat.
In a local Windows window, the extension falls back to starting redsat lsp through wsl.exe
when no Windows redsat is on the PATH.
The extension’s own README.md documents its settings (such as redsat.server.path) and these
details in full.
Other editors
Any editor with a Language Server Protocol client can use redsat lsp: it speaks LSP over
standard input and output.
Knowns and unknowns
Every value in a RedSAT program is either known or unknown, and that one idea explains most of the language.
Known values: ordinary computation
A variable with a value is known, and so is anything computed only from known values. RedSAT simply computes these, as any language would:
var width = 7
var height = 6
var area = width * height
print "area = {area}"
print 2 ^ 100
area = 42
1267650600228229401496703205376
print shows its arguments, separated by spaces. Notice the last line: integers in RedSAT are
exact. There is no 64-bit limit and no overflow, ever.
Unknowns: what the solver finds
A var without a value is an unknown. Its value is what solve will look for:
var x: int[0..=10] // an unknown integer from 0 to 10
var y = 2 * x + 1 // depends on x, so y is not known either
require y == 15
solve x, y
x = 7, y = 15
y has a value, 2 * x + 1, but that value depends on the unknown x. RedSAT does not need to
know x to work with y: it builds a little circuit that computes 2 * x + 1 from the bits of
x, and the SAT solver figures out the rest.
Whether a variable is known, unknown, or derived from unknowns like y follows from how you
declare and use it, not from a keyword:
| Declaration | What it is |
|---|---|
var x | a fresh unknown; its type is inferred from how it is used |
var x: int[0..=9] | a fresh unknown with an explicit type |
var x = expression | known if the expression is, otherwise derived from unknowns |
You can only print what you know
Outside a solve, an unknown has no value yet, so it cannot be printed:
var x: int[0..=9]
require x > 4
print "x is {x}"
error: this value depends on unknowns, so it cannot be shown here
--> main.rsat:3:14
|
3 | print "x is {x}"
| ^
= help: print it inside a `solve` body, where every unknown has a value
Inside the body of a solve, every unknown has been given a value, so there you can print and
compute with it freely:
var x: int[0..=9]
require x > 4
solve x {
print "x is {x}, and x squared is {x * x}"
}
x is 9, and x squared is 81
Exact arithmetic, also on unknowns
Arithmetic on unknowns is just as exact as on known values. RedSAT works out the range of every intermediate result and gives it enough bits, so nothing can overflow:
var a, b: uint<8> // each from 0 to 255
require a + b == 510 // no wraparound: the sum really can be 510
solve a, b
a = 255, b = 255
Bounds like uint<8> limit what a variable may hold; they do not make arithmetic wrap. If you
want the modular arithmetic of a CPU, write it out, and it means exactly what it says:
var a, b: uint<8>
require a == 200
require (a + b) % 256 == 4 // 8-bit addition that wraps around
solve a, b
a = 200, b = 60
Variables change; requirements see the current value
Variables can be assigned again. Each assignment creates a new version of the variable, and a
require refers to the version current at that point:
var x: int[0..=9]
var y = x
require y > 5 // here y is x
y = y * 2
require y < 15 // here y is 2 * x
solve all x
x = 6
x = 7
This is what makes loops useful. Here total is built up one step at a time; in the end it
stands for 1*x + 2*x + 3*x + 4*x:
var x: int[0..=100]
var total = 0
for i in 1..=4 {
total = total + i * x
}
require total == 50
solve x, total
x = 5, total = 50
The known part runs first
A good way to think about a RedSAT program: all the known computation runs first, like a script
that builds the problem. Loops over known ranges are unrolled, functions are called, and every
require on unknowns is collected. Only then does the solver get to work.
That is why some things must be known when the program runs: array lengths, loop ranges, type
bounds, limit counts, exponents and shift amounts. Using an unknown there is an error:
var n: int[1..=5]
for i in 0..n {
require i < 10
}
error: a range bound must be known at compile time
--> main.rsat:2:13
|
2 | for i in 0..n {
| ^ this depends on unknowns
It also means that ordinary code is a powerful tool for generating constraints. In N-Queens, a loop over the rows creates every “these two queens must not attack each other” requirement; change one number and you get a bigger board.
Next: the different ways to ask for answers, in Requirements and solving.
Requirements and solving
Two statements do the real work in every RedSAT program: require says what must be true, and
solve asks for answers.
require
require takes a condition, a bool, that every answer must satisfy. Several requirements
must all hold together, so these two programs mean the same:
var x, y: int[0..=9]
require x + y == 10
require x - y == 4
solve x, y
x = 7, y = 3
var x, y: int[0..=9]
require x + y == 10 and x - y == 4
solve x, y
x = 7, y = 3
Splitting requirements over several lines reads better, and it also helps when there is no solution: RedSAT points at the requirements that contradict each other.
solve: the first answer
solve followed by some variables finds one answer and prints those variables:
var x, y: int[1..=9]
require x * y == 12
solve x, y
x = 4, y = 3
Which answer comes first is up to the solver. If you need a particular one, say so with more requirements, or ask for the best one.
You can list any expressions, not only variables. RedSAT then looks for values of those expressions:
var x, y: int[1..=9]
require x * y == 12
solve all x + y
x + y = 7
x + y = 8
A bare solve, with nothing after it, shows every variable whose value depends on unknowns:
var a, b: bool
var both = a and b
require a or b
require not both
solve all
a = true, b = false, both = false
a = false, b = true, both = false
solve all: every answer
var x, y: int[1..=9]
require x * y == 12
solve all x, y
x = 4, y = 3
x = 6, y = 2
x = 2, y = 6
x = 3, y = 4
Add limit K to stop after K answers. It also works without all, to ask for the first K:
var x, y: int[1..=9]
require x * y == 12
solve x, y limit 2
x = 4, y = 3
x = 6, y = 2
solve unique: exactly one answer
solve unique finds an answer and then proves that no other one exists. That takes a second
call to the solver, and it is great for puzzles, where a well-made puzzle has exactly one
solution. If there are more, the program stops with an error that shows two of them:
var a, b: int[0..=3]
require a + b == 3
solve unique a, b
error: `solve unique` found more than one solution
--> main.rsat:3:1
|
3 | solve unique a, b
| ^^^^^^^^^^^^^^^^^
= note: one solution: a = 0, b = 3
= note: another one: a = 1, b = 2
limit cannot be combined with unique.
Bodies: doing something with each answer
A solve can have a body in { … }. It runs once per answer, with every unknown set to its
value, so inside it everything is known and you can print, format and compute as you like:
var x, y: int[1..=9]
require x * y == 12 and x <= y
solve all x, y {
print "12 = {x} × {y}"
}
12 = 2 × 6
12 = 3 × 4
A body can also update ordinary variables declared outside it. This counts the answers instead of printing them:
var count = 0
var x, y: int[1..=9]
require x * y == 12
solve all x, y {
count = count + 1
}
print "12 is a product of two digits in {count} ways"
12 is a product of two digits in 4 ways
A body cannot add requirements (require) or start another solve: by the time it runs, the
answer has already been found.
else: when there is no answer
An else block after a solve runs when there is no answer at all:
var x: int[0..=9]
require x * x == 50
solve x {
print "{x} squared is 50"
} else {
print "50 is not the square of a digit"
}
50 is not the square of a digit
Without else, RedSAT prints no solution and explains why: see
When there is no solution.
Projection: only the listed variables count
The variables listed after solve decide what counts as a different answer. All other unknowns
only have to exist.
Which numbers from 1 to 20 are the sum of two squares, a² + b²?
var total: int[1..=20]
var a, b: int[0..=5]
require a * a + b * b == total
solve all total
total = 18
total = 20
total = 16
total = 17
total = 9
total = 10
total = 13
total = 8
total = 4
total = 5
total = 1
total = 2
Many totals can be made in several ways (5 = 1² + 2² = 2² + 1²), but since only total is
listed, each total is reported once. a and b are witnesses: they only need to exist.
Several solves: constraints accumulate
A program can have many solve statements. Each one sees every require made before it,
not just those since the previous solve:
var x: int[0..=9]
require x > 6
solve all x
require x % 2 == 0
solve all x
x = 8
x = 9
x = 7
x = 8
This lets known code between solves steer the search, for example to tighten a requirement
and solve again. The flip side: if you put two unrelated puzzles in one file, the second one
also has to satisfy the first one’s requirements. Keep unrelated problems in separate files.
solve must be a top-level statement: it cannot appear inside a function, or inside an if
whose condition depends on unknowns.
Stepping through answers interactively
Run a program with redsat --interactive and RedSAT pauses after each answer of every solve:
press Enter for the next one, a for all the rest, or q to move on. It is a convenient way to
explore a problem with many answers without editing the program.
Summary
solve [all | unique] <expressions> [limit K] [minimize E | maximize E] [{ body }] [else { body }]
| Form | Finds |
|---|---|
solve x, y | the first answer |
solve x, y limit 3 | the first three answers |
solve all x, y | every answer (limit K stops after K) |
solve unique x, y | the answer, plus a proof that it is the only one |
solve x minimize e | an answer with the smallest e: see Optimization |
solve | the first answer, showing every variable that depends on unknowns |
Types
Every unknown has a type, and the type says which values the solver may choose from. Types are often inferred, but writing them down is the easiest way to tell RedSAT (and your readers) what an unknown stands for.
Here is the whole family at a glance. The sections below show each one in action.
var N = 8
var flag: bool // true or false
var count: int // any integer; RedSAT infers the range
var digit: int[0..=9] // 0, 1, 2, …, 9
var die: int[1..=6] // 1, 2, …, 6
var index: int[0..8] // 0, 1, …, 7: the indices of an 8-element array
var celsius: int[-40..=50] // negative bounds are fine
var level: int[0..N] // bounds may be any known expression
var byte: uint<8> // what an unsigned 8-bit number holds: 0 … 255
var sample: int<16> // what a signed 16-bit number holds: −32768 … 32767
var letter: char // a character, such as 'q'
var name: string[1..=10] // a string of 1 to 10 characters, such as "kayak"
var row: [int[1..=9]; 9] // nine digits, each from 1 to 9
var board: [[bool; 8]; 8] // an 8 × 8 grid of yes/no cells
enum Color { Red, Green, Blue }
var paint: Color // Red, Green or Blue
struct Point { x: int, y: int }
var corner: Point // a point with integer coordinates
bool
A bool is true or false. Yes/no decisions are naturally booleans: is this item packed, is
this person a knight, is it raining?
var raining, umbrella: bool
require raining implies umbrella
require raining
solve raining, umbrella
raining = true, umbrella = true
int
An int is a mathematical integer, as small or as large as needed. A plain int leaves the
range open, and RedSAT infers it from your requirements:
var x: int
require x * x == 49 and x < 0
solve x
x = -7
From x * x == 49, RedSAT works out that x lies between −7 and 7 and gives it just enough
bits. When the requirements leave an integer unbounded, RedSAT warns you and searches with
growing bounds: see Unbounded integers.
Integer ranges: int[lo..hi] and int[lo..=hi]
Most of the time you know the range of an unknown, and saying so is a good idea: smaller ranges mean smaller problems. There are two ways to write a range, and they differ only in whether the upper end is included:
| Range | Includes hi? | Example | Values |
|---|---|---|---|
lo..hi | no | int[0..10] | 0, 1, …, 9 |
lo..=hi | yes | int[0..=9] | 0, 1, …, 9 |
So int[0..10] and int[0..=9] are the same type. Ranges look the same in loops and
comprehensions, so you can see the difference directly:
print [i for i in 1..4]
print [i for i in 1..=4]
[1, 2, 3]
[1, 2, 3, 4]
Each form reads naturally in a different situation:
..(exclusive) fits counting and indexing.for i in 0..Nruns exactlyNtimes, andint[0..N]is exactly the set of valid indices of an array of lengthN...=(inclusive) fits natural bounds. “A digit from 0 to 9” isint[0..=9], and “a roll of a die” isint[1..=6].
If you are used to Rust, this is the same convention. A range with no values is an error, which catches the classic off-by-one:
var digit: int[5..5]
error: the range `5..5` contains no values
--> main.rsat:1:16
|
1 | var digit: int[5..5]
| ^^^^
= note: `lo..hi` excludes `hi`, while `lo..=hi` includes it
Fixed-width integers: int<N> and uint<N>
uint<N> holds what an unsigned N-bit number can hold, 0 to 2^N − 1, and int<N> what a
signed one can hold, −2^(N−1) to 2^(N−1) − 1. They are handy when a problem is about
machine words:
var smallest: int<8>
solve smallest minimize smallest
var largest: uint<8>
solve largest maximize largest
smallest = -128
largest = 255
Bounds restrict variables, not arithmetic
A bounded type limits which values a variable may hold. Arithmetic is always exact: with
a, b: uint<8>, the sum a + b can be 510. Storing a value into a bounded variable adds the
requirement that it fits:
var a, b: uint<8>
var total: uint<8> = a + b // requires a + b <= 255
require a == 200
solve a, b, total maximize b
a = 200, b = 55, total = 255
Explicit bounds always win: RedSAT may infer a narrower range inside them, but never a wider one. If your requirements need a value outside the declared range, the correct answer is “no solution”. A known value outside the range is reported right away:
var level: int[0..10] = 10
error: 10 is outside the declared range [0, 9]
--> main.rsat:1:25
|
1 | var level: int[0..10] = 10
| ^^
char
A char is a Unicode character, written in single quotes: 'a', 'Z', '7', '\n'.
Characters can be compared (<, >=, …), tested against a range or a string with in, and
converted to and from their code with ord and chr:
var c: char
require c in 'a'..='z'
require ord(c) - ord('a') == 7
solve c
c = 'h'
string
A string is a sequence of characters, written in double quotes. Known strings work as in any
language: len(s), s[i], s + t and reverse(s).
An unknown string needs a range of lengths, written like an integer range:
string[3..=5] holds strings of 3 to 5 characters. The length itself is an unknown, and so is
every character:
var word: string[3..=5]
require all(c in 'a'..='c' for c in word)
require reverse(word) == word and len(word) == 4
solve all word limit 3
word = "aaaa"
word = "acca"
word = "abba"
A plain string works too, but RedSAT then has to guess a maximum length, 32, and warns you:
var s: string
require s + "!" == "hi!"
solve s
s = "hi"
warning: `s` has no length bounds; lengths up to 32 are considered
--> main.rsat:1:5
|
1 | var s: string
| ^
= help: declare its lengths, e.g. `var s: string[1..=10]`
Strings cannot be changed in place (s[0] = 'x' is an error): build a new one with +.
Arrays: [T; N]
[T; N] holds exactly N values of type T. The length must be known when the program runs,
but the elements can be unknowns, and so can an index:
var row: [int[1..=4]; 4]
require all_different(row)
require row[0] == 2 and row[3] < row[1]
solve all row limit 3
row = [2, 3, 4, 1]
row = [2, 4, 1, 3]
row = [2, 4, 3, 1]
Arrays nest: [[int[1..=9]; 9]; 9] is a Sudoku grid, read as grid[r][c]. Known arrays are
written as lists, [4, 8, 15], and their type, length included, comes from the list. For
functions that accept arrays of any length, see Functions.
Mixing knowns and unknowns: ?
Sometimes part of a value is given and part is to be found, like a Sudoku grid with some digits
filled in. Write ? for each missing piece. Every ? is a fresh, anonymous unknown, whose type
comes from the declaration around it:
var row: [int[1..=4]; 4] = [1, ?, ?, 4]
require all_different(row) and row[1] < row[2]
solve row
row = [1, 2, 3, 4]
? works anywhere a single value of a known type is expected: an array element, a struct field
(Point(1, ?)), or a whole value (var p: Point = ?).
Enums
An enum is a type with a fixed set of named values. Enums make models read like the problem they describe:
enum Drink { Tea, Coffee, Juice }
var alice, bob: Drink
require alice != bob
require alice != Drink.Coffee
require bob == Drink.Coffee or bob == Drink.Juice
solve all alice, bob
alice = Juice, bob = Coffee
alice = Tea, bob = Coffee
alice = Tea, bob = Juice
Enum values are written Drink.Tea and compared with == and !=. Enums are declared at the
top level of a file.
Structs
A struct groups named fields into one value. Fields can have any type, including bounded integers, arrays and other structs:
struct Point { x: int[-5..=5], y: int[-5..=5] }
var p: Point
require p.x * p.x + p.y * p.y == 25 and p.x > 0 and p.y > 0
solve all p
var origin = Point(x: 0, y: 0) // fields by name…
var corner = Point(3, 4) // …or by position
corner.x = corner.x + 1
print origin, corner, corner.x
p = Point(x: 4, y: 3)
p = Point(x: 3, y: 4)
Point(x: 0, y: 0) Point(x: 4, y: 4) 4
An unknown struct is simply a bundle of unknowns, one per field. Structs, too, are declared at the top level.
Type inference
You can leave out the type of an unknown whenever its use settles it: var x, y followed by
x * y == n makes both int, and using a variable with and makes it a bool. When nothing
settles it, RedSAT asks you to annotate it:
var mystery
solve mystery
error: cannot infer the type of `mystery`
--> main.rsat:1:5
|
1 | var mystery
| ^^^^^^^ declared here
= help: use it in a way that determines its type, or annotate it: `var mystery: int` or `var mystery: bool`
Some teams prefer every unknown to carry a type. The explicit-types compiler option, part of
strict mode, makes annotations mandatory.
The types reference has the complete rules.
Expressions and operators
Expressions work the same on known values and on unknowns: x + 1 means the same whether x
is 41 or something the solver has yet to find. This chapter tours the operators; the
expressions reference has the full precedence table.
Arithmetic
+, -, *, /, % and ^ (power) work on integers, and are exact: results are never
truncated to some number of bits.
print 1 + 2 * 3, 2 ^ 10, (1 + 2) * 3
print 10 / 3, 10 % 3
7 1024 9
3 1
Division rounds so that the remainder is never negative (this is called Euclidean division). For positive numbers that is the usual answer; for negative ones it differs from languages like C, Java or Rust:
print -7 / 2, -7 % 2
print 7 / -2, 7 % -2
-4 1
-3 1
The rule is simple: a == (a / b) * b + a % b, and a % b lies in 0..abs(b). In particular
x % 2 is always 0 or 1, so x % 2 == 1 is a reliable test for odd numbers, even negative
ones.
/ and % work on unknowns too, also by unknown divisors. Dividing by an unknown adds the
requirement that it is not zero:
var d: int[-4..=4]
require 12 / d == -3
solve all d
d = -4
The exponent of ^ must be known (x ^ 3 is fine, 2 ^ x is not), and so must the shift
amount of << and >>. See Performance tips for why
multiplying two unknowns is costlier than it looks.
Comparisons
== and != work on every type: numbers, booleans, characters, strings, arrays, enums and
structs. <, <=, > and >= work on integers and characters.
Comparisons do not chain. Mathematicians write 0 < x < 10, but RedSAT asks you to spell it
out:
var x: int[0..=20]
require 0 < x < 10
error: comparisons cannot be chained
--> main.rsat:2:15
|
2 | require 0 < x < 10
| ^
= help: write `a < b and b < c` instead of `a < b < c`
(x in 1..10 is a neat alternative, see Membership below.)
Logic
The logical operators are words:
| Operator | True when |
|---|---|
not a | a is false |
a and b | both are true |
a or b | at least one is true |
a xor b | exactly one is true |
a implies b | a is false, or b is true |
a iff b | both are true or both are false |
implies and iff are rarely found in programming languages, but they are everyday tools for
stating requirements. “If it rains, take an umbrella” is require raining implies umbrella,
and “a knight’s statement is true” is require knight iff statement.
Typing &&, || or ! gets you a friendly reminder of the word to use instead.
Guarded evaluation
and, or and implies only evaluate their right-hand side where it matters. When the
left-hand side is an unknown, the right-hand side only has to make sense when the left-hand
side allows it. This makes guards like this one safe, even though i may be out of range:
var xs = [3, -1, 4]
var i: int[0..=5]
require i < len(xs) and xs[i] > 0
solve all i
i = 0
i = 2
Without the guard, xs[i] alone would require i to be a valid index. An if expression
(below) guards its branches the same way.
Precedence, briefly
Operators bind in the order you would expect from mathematics: ^ before * before +, then
comparisons, then not, and, or. Two differences from C-like languages are worth knowing:
- Bitwise operators bind tighter than comparisons, so
x & 1 == 1means(x & 1) == 1. notbinds looser than comparisons, sonot x == 3meansnot (x == 3).
var x: int[0..=7]
require not x == 3 and x & 1 == 1 and x > 1
solve all x
x = 7
x = 5
When in doubt, add parentheses.
Bitwise operators
& (and), | (or), xor, << and >> work on integers, bit by bit, as on two’s-complement
numbers. xor does double duty: on booleans it is logical, on integers bitwise.
print 12 & 10, 12 | 10, 12 xor 10
print 1 << 4, 256 >> 4, -16 >> 2
8 14 6
16 16 -4
>> rounds towards minus infinity, like division by a power of two. The standard library has
bit and popcount for working with single bits.
Membership: in
x in … tests whether a value lies in a range, an array or a string:
print 3 in 1..3, 3 in 1..=3
print 4 in [1, 4, 9], 'e' in "aeiou"
false true
true true
Comprehensions and aggregates
A comprehension builds an array from a loop, with optional if filters, and several fors
nest:
print [x * x for x in 1..=5 if x != 3]
print [[i, j] for i in 0..3 for j in i + 1..3]
[1, 4, 16, 25]
[[0, 1], [0, 2], [1, 2]]
The aggregates sum, count, all, any, min and max take an array, or a
comprehension written straight inside the parentheses:
var xs = [4, 8, 15, 16, 23, 42]
print sum(xs), min(xs), max(xs)
print count(x % 2 == 0 for x in xs), all(x > 0 for x in xs), any(x > 40 for x in xs)
108 4 42
4 true true
This is where models get compact. A filter that depends on unknowns is allowed inside sum,
count, all and any: it decides, per element, whether that element takes part. Pick three
of the numbers so that they add up to 47:
var xs = [4, 8, 15, 16, 23, 42]
var pick: [bool; 6]
require count(pick) == 3
require sum(xs[i] for i in 0..6 if pick[i]) == 47
solve all pick {
print [xs[i] for i in 0..6 if pick[i]]
}
[8, 16, 23]
Inside the solve body, pick is known, so the comprehension [… if pick[i]] is fine there.
Outside a body, an array comprehension cannot filter on unknowns, because the length of the
array would depend on them:
var take: [bool; 3]
var chosen = [i for i in 0..3 if take[i]]
error: an array comprehension cannot filter on unknowns: its length would depend on them
--> main.rsat:2:14
|
2 | var chosen = [i for i in 0..3 if take[i]]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
= help: aggregate with `sum`, `count`, `all`, `any`, `len` or `all_different`, or move the condition into the element
if as a value
if can be used as an expression. It needs both branches, and else if chains work:
var a, b: int[0..=9]
var bigger = if a > b { a } else { b }
var trend = if a == b { "flat" } else if a < b { "rising" } else { "falling" }
require bigger == 7 and a + b == 10
solve all a, b {
print "{a}, {b}: the bigger one is {bigger}, {trend}"
}
3, 7: the bigger one is 7, rising
7, 3: the bigger one is 7, falling
When the condition depends on unknowns, both branches are computed, and the result is “the first if the condition holds, otherwise the second”.
Strings and interpolation
{…} inside a string inserts the value of any expression. To write a literal brace, escape it:
var name = "Ada"
print "Hello, {name}! Your name has {len(name)} letters."
print "braces: \{ and \}, a quote: \", a backslash: \\"
print "a tab:\tthen more"
Hello, Ada! Your name has 3 letters.
braces: { and }, a quote: ", a backslash: \
a tab: then more
The escapes are \n, \t, \r, \0, \\, \", \', \{ and \}.
+ joins strings, and also arrays:
print "ab" + "cd", [1, 2] + [3]
abcd [1, 2, 3]
Built-in functions
A handful of functions are built into the language: abs, isqrt, min, max, len, sum,
count, all, any, all_different, reverse, ord and chr. On top of them, a
standard library written in RedSAT itself adds
exactly, sorted, lex_less, is_digit and many more. All of them work on unknowns. The
built-in functions reference describes each one.
Control flow over unknowns
RedSAT has the control flow you know: if, for and while. On known values they behave
exactly as in any language. The interesting part is what happens when a condition depends on
unknowns, because then RedSAT cannot know which way the program goes. It handles every way,
and lets the solver decide.
if
When the condition is known, if is ordinary: only the branch taken is run. When the condition
depends on unknowns, both branches are compiled, and every variable assigned in them gets
the value “this if the condition holds, otherwise that”.
Two numbers between 0 and 100 add up to 50, and the bigger one is 42. Which are they?
var a, b: int[0..=100]
var biggest = a
if b > a {
biggest = b // biggest becomes: b if b > a, otherwise a
}
require biggest == 42
require a + b == 50
solve all a, b
a = 8, b = 42
a = 42, b = 8
This is ordinary imperative code, the kind you would write for known numbers, and it works on
unknowns unchanged. else if chains work too. Here is a tax table with three brackets; which
income pays exactly 9000 in tax?
var income: int[0..=10000]
var tax = 0
if income < 1000 {
tax = income
} else if income <= 5000 {
tax = 2 * income
} else {
tax = 2 * income + 500
}
require tax == 9000
solve all income {
print "an income of {income} pays {tax}"
}
an income of 4500 pays 9000
require inside an if
A require inside a branch only applies when that branch is taken. Under a condition c,
require p means “c implies p”:
var big: bool
var x: int[0..=9]
if big {
require x > 7
} else {
require x < 2
}
solve all big, x
big = false, x = 0
big = false, x = 1
big = true, x = 8
big = true, x = 9
Printing needs a known path
Under a condition that depends on unknowns, RedSAT cannot know whether the program would get there, so it cannot print:
var x: int[0..=9]
if x > 5 {
print "big"
}
error: cannot print under a condition that depends on unknowns
--> main.rsat:3:5
|
3 | print "big"
| ^^^^^^^^^^^
= help: print inside a `solve` body instead
for
for loops over a range, an array or a string:
for i in 0..3 {
print "i = {i}"
}
for word in ["red", "sat"] {
print word
}
for c in "hey" {
print c
}
i = 0
i = 1
i = 2
red
sat
h
e
y
The range of a for must be known: RedSAT unrolls the loop, running the body once for each
value. The loop variable is known in each copy of the body, which makes for the main tool for
generating requirements. This checks every pair of queens on an N×N board, however big N
is:
var N = 8
var queen: [int[0..N]; N] // queen[r]: the column of the queen in row r
for r1 in 0..N {
for r2 in r1 + 1..N {
require abs(queen[r1] - queen[r2]) != r2 - r1
}
}
(The whole program is in the cookbook.)
Looping over a string of unknown length runs the body for every position up to the string’s maximum length, each one guarded by “this position is within the string”. So this just works:
var word: string[1..=3]
var vowels = 0
for c in word {
if c in "aeiou" {
vowels = vowels + 1
}
}
require all(c in 'a'..='e' for c in word)
require vowels == 2 and word[0] == 'b'
solve all word
word = "baa"
word = "bae"
word = "bea"
word = "bee"
The loop variable cannot be assigned to.
while
A while loop whose condition is known runs as usual. How many steps does 27 take to reach 1 in
the Collatz sequence?
var n = 27
var steps = 0
while n != 1 {
n = if n % 2 == 0 { n / 2 } else { 3 * n + 1 }
steps = steps + 1
}
print "27 reaches 1 after {steps} steps"
27 reaches 1 after 111 steps
When the condition depends on unknowns, RedSAT cannot know how often the loop runs, so you must give it a bound, the most iterations it may take:
var x: int[0..=100]
var n = x
while n >= 10 bound 3 {
n = n - 10
}
require n == 5
solve all x
x = 5
x = 15
x = 25
x = 35
while cond bound K unrolls the loop K times, each iteration guarded by the condition, and
then requires that the loop has finished. That is why x = 45 is not an answer: it would
need four iterations. Pick a bound that is large enough for every answer you want, but no
larger, since each iteration adds to the size of the problem.
Forgetting the bound is an error:
var n: int[1..=9]
while n > 1 {
n = n - 1
}
error: this loop's condition depends on unknowns
--> main.rsat:2:7
|
2 | while n > 1 {
| ^^^^^
= help: add a maximum number of iterations: `while … bound 100 { … }`
A known loop is allowed up to ten million iterations before RedSAT assumes it never ends.
and, or and if guard what follows
As shown in Expressions, a and b, a or b,
a implies b and if expressions only evaluate their second part where it matters. Together
with symbolic if, this means that defensive code, such as checking an index before using it,
works on unknowns exactly as you would hope.
Functions
Functions let you name a piece of a model and reuse it. They look like functions in any language, and they work on known values and on unknowns alike.
fn area(width: int, height: int) -> int {
return width * height
}
print area(6, 7)
var w, h: int[1..=10]
require area(w, h) == 24 and w < h
solve all w, h
42
w = 4, h = 6
w = 3, h = 8
Declaring functions
fn name(parameter: type, …) -> result_type { … }declares a function. Every parameter needs a type; the result type is left out for functions that return nothing.- Functions are declared at the top level of a file, and can be used anywhere in it, also above their declaration.
- An array parameter may leave out the length, so
xs: [int]accepts arrays of any length. - A function body can contain anything a program can: variables (including unknowns),
if, loops,requireand calls to other functions. It cannot containsolve.
fn mean(xs: [int]) -> int {
return sum(xs) / len(xs)
}
print mean([2, 4, 9]), mean([1, 2, 3, 4, 5])
5 3
A function whose only parameter is an array can also be called with a comprehension written directly inside its parentheses, like the built-in aggregates:
fn mean(xs: [int]) -> int {
return sum(xs) / len(xs)
}
print mean(x * x for x in 1..=3)
4
Functions that add requirements
A function without a result type is useful for packaging up requirements. Each call creates its
own copies of the function’s variables, so here every call gets a fresh root:
// Requires that n is a perfect square (n at most 10000).
fn require_square(n: int) {
var root: int[0..=100]
require root * root == n
}
var x: int[1..=100]
require_square(x)
require_square(x + 9)
solve all x
x = 16
Functions only see their parameters
A function sees its parameters and its own variables, and nothing else. That keeps functions self-contained, and a mistake here gets a clear message:
var limit = 10
fn small(x: int) -> bool {
return x < limit
}
error: unknown variable `limit`
--> main.rsat:3:16
|
3 | return x < limit
| ^^^^^ not declared
= note: functions can only use their own parameters and variables
= help: pass `limit` to the function as a parameter
Early returns work on unknowns
You can return from the middle of a function, also under a condition that depends on
unknowns. RedSAT keeps track of “has the function returned yet?” for every path, so ordinary
early-return code means what it says:
fn clamp_to(v: int, lo: int, hi: int) -> int {
if v < lo { return lo }
if v > hi { return hi }
return v
}
var x: int[-20..=20]
require clamp_to(x, 0, 10) == 10 and x < 13
solve all x
x = 12
x = 11
x = 10
This works inside loops too. Find arrays whose first positive element is at position 2:
fn first_positive(xs: [int]) -> int {
for i in 0..len(xs) {
if xs[i] > 0 { return i }
}
return -1
}
var v: [int[-1..=1]; 3]
require first_positive(v) == 2
solve all v
v = [-1, -1, 1]
v = [0, -1, 1]
v = [0, 0, 1]
v = [-1, 0, 1]
A function with a result type must return a value on every path; RedSAT checks this for you.
How calls work: inlining
RedSAT does not “call” functions at run time the way a CPU does. Every call is inlined: the function’s body is run right there, with the arguments in place of its parameters. On known arguments that is just computation. On unknown arguments, the body’s work becomes part of the circuit, once per call.
Two consequences are worth knowing:
-
Recursion is fine when it stops on known values. Here every call has a known
n, so the recursion unfolds completely while the program runs:fn fib(n: int) -> int { if n < 2 { return n } return fib(n - 1) + fib(n - 2) } print [fib(i) for i in 0..12][0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]If the stopping condition depends on unknowns, the unfolding never ends. RedSAT stops after 200 nested calls and tells you:
fn down(n: int) -> int { if n == 0 { return 0 } return down(n - 1) } var x: int[0..=5] require down(x) == 0error: calls nested more than 200 deep --> main.rsat:3:12 | 3 | return down(n - 1) | ^^^^^^^^^^^ ::: main.rsat:6:9 | 6 | require down(x) == 0 | ^^^^^^^ in this call to `down` = note: functions are inlined, so recursion must stop based on values known at compile timeRewrite such a function with a loop over a known range instead, or with
while … bound. -
Each call adds to the problem. A function that multiplies two unknowns adds a multiplier circuit every time it is called on unknowns. That is usually fine, but it is worth keeping in mind inside big loops.
Arguments
Arguments are passed by position. Named arguments, f(x: 1), are only for building
structs.
Your functions and the standard library
RedSAT’s standard library is written in RedSAT and available in every program. If you declare a function with the same name as one of its functions, yours wins, so adding a function to the standard library can never break your program:
fn sign(x: int) -> int {
return 42
}
print sign(-3)
42
Your version replaces the standard one in your code only. Shadowing is lexical: the
standard library’s own functions keep calling the library’s versions. For example, the
standard is_letter calls is_lower, and redefining is_lower does not change is_letter:
fn is_lower(c: char) -> bool {
return false
}
print is_lower('a'), is_letter('a')
false true
The built-in functions such as sum and len are part of the language itself, and their names
cannot be reused for functions.
Documenting your functions
Lines starting with /// right above a function are its documentation. Editors show it when
you hover the function’s name, in the completion list, and in the signature help that pops up
while you type its arguments (in VS Code and in the playground). The standard library documents
its functions the same way.
/// The larger of `a` and `b`, but never above 9.
fn capped_max(a: int, b: int) -> int {
return min(max(a, b), 9)
}
print capped_max(4, 12)
9
Imports
As models grow, you will want to share functions, enums and structs between programs. import
brings in everything another file declares.
A module and a program
A file meant to be imported, a module, contains declarations only. Here are two. The first holds a small helper:
fn square(x: int) -> int {
return x * x
}
The second builds on it, so it imports it:
import "lib/squares.rsat"
struct Point { x: int[-10..=10], y: int[-10..=10] }
fn distance_squared(a: Point, b: Point) -> int {
return square(a.x - b.x) + square(a.y - b.y)
}
A program next to geometry.rsat can now use Point and distance_squared. Which points with
positive coordinates lie at distance 5 from the origin?
import "geometry.rsat"
var origin = Point(0, 0)
var q: Point
require distance_squared(origin, q) == 25 and q.x > 0 and q.y > 0
solve all q
q = Point(x: 4, y: 3)
q = Point(x: 3, y: 4)
The rules
- Paths are relative to the importing file.
geometry.rsatsaysimport "lib/squares.rsat", which means thelibdirectory next togeometry.rsat, wherever the program that importsgeometry.rsatlives. - Imports are transitive. Importing
geometry.rsatalso brings in what it imports, so the program above could callsquaretoo. - Each file is loaded once, however many times it is imported.
- Everything shares one namespace. Declaring the same name in two files is an error, just like declaring it twice in one file.
- Imports go at the top level of a file.
Modules only declare
An imported file may only contain fn, enum, struct and further imports. Statements that
do something, like var, require, print or solve, belong in the program, so a module
can be imported by many programs without side effects. Here is a file that breaks the rule:
fn greeting() -> string {
return "hello"
}
print greeting()
Run on its own, it is a fine program. Imported, it is rejected, with a pointer to the offending statement and to the import:
import "greeting.rsat"
error: an imported file may only declare functions, enums and structs
--> greeting.rsat:4:1
|
4 | print greeting()
| ^^^^^^^^^^^^^^^^
::: main.rsat:1:1
|
1 | import "greeting.rsat"
| ^^^^^^^^^^^^^^^^^^^^^^ imported here
Importing a file that does not exist is an error too, which names the file and the reason it could not be opened.
The standard library
Every program implicitly has access to RedSAT’s
standard library, with no import needed. It is written in
RedSAT, so you can read it to see how its functions work, and your own functions with the same
name take precedence over it (see Functions).
Optimization
Often any answer will not do: you want the best one. Add minimize or maximize to a solve,
followed by the expression to optimize.
How do you make 289 cents with as few coins as possible?
var amount = 289
var quarters, dimes, nickels, pennies
require quarters >= 0 and dimes >= 0 and nickels >= 0 and pennies >= 0
require 25 * quarters + 10 * dimes + 5 * nickels + pennies == amount
var coins = quarters + dimes + nickels + pennies
solve quarters, dimes, nickels, pennies minimize coins {
print "{coins} coins: {quarters} quarters, {dimes} dimes, {nickels} nickels, {pennies} pennies"
}
16 coins: 11 quarters, 1 dimes, 0 nickels, 4 pennies
The objective can be any integer expression: a variable, a sum, a product, the max of several
values (as in scheduling, where the latest finishing time is
minimized), or a sum filtered by unknowns (as in the knapsack).
Every optimal answer
There may be several answers that are equally good. solve all … minimize (or maximize)
lists all of them. Which rectangles with a perimeter of 18 have the largest area?
var w, h: int[1..=20]
require 2 * (w + h) == 18
solve all w, h maximize w * h {
print "{w} × {h}: area {w * h}"
}
4 × 5: area 20
5 × 4: area 20
limit K caps the number of optimal answers listed, as usual.
Several goals at once
To optimize one thing first and use another to break ties, weight them so that the first always
dominates. If x matters more than y and y never exceeds 10, minimize 100 * x + y:
var x, y: int[0..=10]
require x + y >= 7
solve x, y minimize 100 * x + y
x = 0, y = 7
How it works
RedSAT finds the optimum by binary search over the objective’s value. It first finds any
answer, then repeatedly asks the solver “is there an answer whose objective is at most m?”,
halving the gap between the best answer so far and the best value still possible. The range it
searches comes from the same domain inference that sizes every
unknown.
So the number of SAT calls grows with the number of bits of the objective, not its size: an objective that can range over a trillion values needs only about 40 calls. Each probe is a temporary assumption, so failed probes leave nothing behind.
Counts are optimized differently. When the objective counts booleans (count(…), or a
sum filtered by unknowns whose weights take at most four distinct values), RedSAT works from
below instead. It asks for an answer where none of the counted conditions holds. When that
is impossible, the solver points at a group of conditions of which at least one must hold: the
optimum is at least 1. RedSAT then allows one of them and asks again, and so on, until an
answer exists. That answer meets the lower bound, so it is optimal. For “fewest violations”
problems (covers, soft constraints, conflicts) this is often orders of magnitude faster: a
minimum vertex cover of an 80-vertex graph takes 0.02 s instead of 3 s.
Run with --verbose to see how many SAT calls an optimization took.
Two things follow from this:
- Tight bounds help. The smaller the objective’s possible range, the fewer probes it needs, and the smaller the circuit behind it.
- A known objective does nothing.
solve x minimize 5simply finds the first answer.
When there is no solution
Sometimes the requirements contradict each other. Maybe the puzzle really has no answer, or maybe the model has a bug. Either way, RedSAT tries to tell you why.
Explanations
When a solve without an else block finds no solution, RedSAT prints no solution and then
explains which requirements cannot hold together:
var x, y: int[0..=10]
var z: int[0..=5]
require x + y == 12
require z > 3
require x > 9
require y > 5
solve x, y
no solution
note: no solution: these requirements cannot all hold together
--> main.rsat:3:9
|
3 | require x + y == 12
| ^^^^^^^^^^^
::: main.rsat:5:9
|
5 | require x > 9
| ^^^^^
::: main.rsat:6:9
|
6 | require y > 5
| ^^^^^
The explanation is minimal: every requirement it lists is needed for the contradiction, and
the ones that have nothing to do with it, like z > 3, are left out. Drop or relax any one of
the listed requirements and the contradiction goes away (though another one may remain).
Requirements created inside loops or functions are reported at the line that wrote them. Three pigeons cannot sit in two holes without sharing:
var hole: [int[0..=3]; 3]
require all_different(hole)
for i in 0..3 {
require hole[i] < 2
}
solve hole
no solution
note: no solution: these requirements cannot all hold together
--> main.rsat:2:9
|
2 | require all_different(hole)
| ^^^^^^^^^^^^^^^^^^^
::: main.rsat:4:13
|
4 | require hole[i] < 2
| ^^^^^^^^^^^
When a single requirement is impossible on its own, RedSAT says so:
var x: int[0..=9]
require x * x == 50
solve x
no solution
note: no solution: this requirement can never hold
--> main.rsat:2:9
|
2 | require x * x == 50
| ^^^^^^^^^^^
A requirement that is false before any solving starts gets a warning of its own:
require 1 + 1 == 3
solve
no solution
warning: this requirement is always false, so the problem has no solution
--> main.rsat:1:9
|
1 | require 1 + 1 == 3
| ^^^^^^^^^^
note: no solution: this requirement can never hold
--> main.rsat:1:9
|
1 | require 1 + 1 == 3
| ^^^^^^^^^^
How explanations are found
Each source line that adds requirements is switched on by its own “selector”. The solver is asked to solve with all selectors on, and when it fails it reports which selectors it needed for its proof. RedSAT then tries dropping them one by one, keeping only those the contradiction cannot do without.
This means solving the problem a few more times. RedSAT skips the explanation when the original proof took more than 10 seconds, and stops minimising after 5 seconds, so a hard problem never gets much slower because of it.
Explanations use the ranges you declared for your unknowns, not the narrower ones RedSAT inferred from the requirements, since those already contain the requirements’ consequences.
Handling “no solution” yourself: else
If “no solution” is an expected outcome, handle it with else. The explanation is then not
printed:
var n = 97
var x, y: int[2..=n]
require x * y == n
solve x, y {
print "{n} = {x} × {y}"
} else {
print "{n} is prime"
}
97 is prime
Unbounded integers
RedSAT needs a finite range for every integer to build its circuit. Usually it infers one from your requirements, but not always: nobody can, in general. (Deciding whether an arbitrary polynomial equation has an integer solution is undecidable, as Matiyasevich proved in 1970.)
When an integer is left unbounded, RedSAT warns you and searches with growing bounds: first
|x| < 2^32, then 2^64, and so on, doubling the number of bits up to 2^256. Any solution it
finds is a genuine one, because the arithmetic is exact:
var x, y: int
require y > 0
require x * x - 2 * y * y == 1
solve all x, y limit 2
x = 3, y = 2
x = 17, y = 12
warning: could not infer bounds for `x`, `y`; searched |value| < 2^32
--> main.rsat:1:5
|
1 | var x, y: int
| ^
= help: add bounds (e.g. `int[0..=1000]`) for a complete search
But “no solution” is then only “no solution within the bounds searched”, and RedSAT says so.
There is no explanation in that case, because there is nothing to explain yet: a larger answer
might exist. (This program limits the search to 64 bits with the max-int-bits option.)
var x, y
require y > 0
require x * x == 2 * y * y
solve x, y
no solution with |x|, |y| < 2^64
warning: could not infer bounds for `x`, `y`; searched |value| < 2^64
--> main.rsat:1:5
|
1 | var x, y
| ^
= help: add bounds (e.g. `int[0..=1000]`) for a complete search
The cure is to give such unknowns bounds. If you would rather be forced to, the
unbounded-ints = "error" compiler option (part of strict
mode) turns the warning into an error:
var x, y: int
require y > 0
require x * x - 2 * y * y == 1
solve all x, y limit 2
error: cannot infer a finite domain for `x`
--> main.rsat:1:5
|
1 | var x, y: int
| ^ unbounded
= note: required by the compiler option unbounded-ints = "error"
= help: give it bounds, e.g. `var x: int[0..=1000]`, or a constraint that limits it
Debugging a model with no solution
When the explanation points at requirements that should be compatible, the bug is usually in one of them. Some techniques that help:
- Solve with fewer requirements. Comment out the requirements the explanation names, one at a time, and look at the answers you get: which one is wrong?
- Check your ranges.
int[0..9]stops at 8. Hovering over an unknown in the editor, or running with--stats, shows the ranges RedSAT inferred. - Remember that constraints accumulate. Every
solvesees all earlier requirements, including those written for an earliersolvein the same file. - Test pieces on known values. Functions work on known values too, so
printa helper’s result for a case you can check by hand.
How to model a problem
The cookbook shows how to express classic problems in RedSAT. Each recipe starts with the
problem in plain language, then builds the model step by step. The full programs, and more, are
in the examples/ directory of the repository.
Writing a model is a skill of its own, different from writing an algorithm. These questions guide almost every model in this cookbook.
1. What does an answer look like?
Pick the unknowns: the smallest set of values that, once known, tell you the whole answer.
- In Sudoku, the answer is the digit in each cell:
[[int[1..=9]; 9]; 9]. - In N-Queens, every row holds exactly one queen, so the answer is the column of each row’s
queen:
[int[0..N]; N]. Choosing this over “a yes/no for every square” makes “one queen per row” true by construction, so it never has to be required. - In a knapsack problem, the answer is a yes/no per item:
[bool; n].
A good choice of unknowns makes many rules automatic. Give each unknown the tightest type
you can: int[1..=9] rather than int.
2. What makes an answer valid?
Turn every rule of the problem into a require. Write them the way the problem states them, and
let loops generate the repetitive ones. “Neighbouring regions have different colours”:
struct Border { a: int, b: int }
var borders = [Border(0, 1), Border(1, 2), Border(0, 2), Border(2, 3)]
var color: [int[0..3]; 4] // three colours, four regions
for border in borders {
require color[border.a] != color[border.b]
}
solve color
color = [1, 2, 0, 1]
The standard library has ready-made building blocks for common rules: all_different,
exactly, at_most, sorted, lex_less and more.
3. What do you want to see?
- One answer?
solve. - Proof that the answer is the only one?
solve unique. - Every answer, or a count?
solve all, with a counter in the body. - The best answer?
minimizeormaximize.
List only the unknowns you care about after solve: the others then only need to exist, and
answers that differ only in them are not repeated.
4. Separate the data from the model
Put the instance, such as the numbers, the names and the grid, in known variables at the top, and
write the rules in terms of them. Then the same model solves any instance: change var N = 8 to
var N = 20 and N-Queens solves a bigger board.
5. Start small, then grow
Solve a tiny instance first and print the answer in a readable form. When it looks right, scale up. If something is slow, see the Performance tips; if there is no solution, see When there is no solution.
The recipes
- Logic puzzles: knights and knaves, a who-owns-what puzzle, and SEND + MORE = MONEY.
- Grid puzzles: Sudoku, N-Queens and magic squares.
- Number puzzles: factoring, Pythagorean triples, digit puzzles and bit patterns.
- Graph colouring: colouring a map with enums and structs.
- Knapsack: picking the most valuable items, with side conditions.
- Scheduling: ordering jobs on a machine to finish as early as possible.
- Counting constraints: a weekly duty roster.
- Symmetry breaking: avoiding answers that are the same in disguise.
Logic puzzles
Logic puzzles are a natural fit: their clues are requirements, and their answer is whatever satisfies all of them.
Knights and knaves
The puzzle. On an island, knights always tell the truth and knaves always lie. You meet two islanders.
- A says: “B is a knave.”
- B says: “A and I are of the same kind.”
Who is what?
The model. One bool per islander: is this one a knight? The key insight is that a
statement is true exactly when its speaker is a knight, whatever the statement is. That is
speaker iff statement:
var a_is_knight, b_is_knight: bool
require a_is_knight iff not b_is_knight // A: "B is a knave"
require b_is_knight iff (a_is_knight iff b_is_knight) // B: "we are alike"
solve unique a_is_knight, b_is_knight {
if a_is_knight { print "A is a knight" } else { print "A is a knave" }
if b_is_knight { print "B is a knight" } else { print "B is a knave" }
}
A is a knight
B is a knave
solve unique also proves there is no other reading of the clues. Inside the body, every value
is known, so the ifs are ordinary code.
Who owns what
The puzzle. Ann, Ben and Cleo each own a different pet (a cat, a dog and a fish) and each prefers a different drink (tea, coffee and juice).
- Ann does not own the dog.
- Ben drinks coffee.
- Whoever owns the fish drinks tea, and whoever owns the dog drinks juice.
Who owns what, and who drinks what?
The model. Enums name the pets and drinks. For each person, one unknown says which pet they
own and one which drink they prefer, and all_different says that no two people share. Each
clue becomes a requirement; clue 3 is about “whoever”, so a loop checks it for every person:
enum Pet { Cat, Dog, Fish }
enum Drink { Tea, Coffee, Juice }
var people = ["Ann", "Ben", "Cleo"]
var pet: [Pet; 3] // pet[p]: the pet of person p
var drink: [Drink; 3] // drink[p]: what person p drinks
require all_different(pet)
require all_different(drink)
// 1. Ann does not own the dog.
require pet[0] != Pet.Dog
// 2. Ben drinks coffee.
require drink[1] == Drink.Coffee
// 3. Whoever owns the fish drinks tea, and whoever owns the dog drinks juice.
for p in 0..3 {
require pet[p] == Pet.Fish implies drink[p] == Drink.Tea
require pet[p] == Pet.Dog implies drink[p] == Drink.Juice
}
solve unique pet, drink {
for p in 0..3 {
print "{people[p]} owns the {pet[p]} and drinks {drink[p]}"
}
}
Ann owns the Fish and drinks Tea
Ben owns the Cat and drinks Coffee
Cleo owns the Dog and drinks Juice
Bigger puzzles of this kind, like the famous Zebra puzzle, work exactly the same way, with
more people, more attributes and more clues. solve unique is the puzzle-setter’s friend: it
tells you whether your clues pin down a single answer, and if they don’t, it shows you two
answers that a further clue must tell apart.
SEND + MORE = MONEY
The puzzle. A classic from 1924. Each letter stands for a different digit, and the leading
letters S and M are not zero:
S E N D
+ M O R E
-----------
M O N E Y
The model. One digit per letter, all_different over all eight, and the column addition
written as a single equation over place values: thousands, hundreds, tens and ones.
var s, e, n, d, m, o, r, y: int[0..=9]
require all_different([s, e, n, d, m, o, r, y])
require s != 0 and m != 0
require ( 1000*s + 100*e + 10*n + d
+ 1000*m + 100*o + 10*r + e
== 10000*m + 1000*o + 100*n + 10*e + y )
solve unique s, e, n, d, m, o, r, y {
print " {s}{e}{n}{d}"
print "+ {m}{o}{r}{e}"
print "= {m}{o}{n}{e}{y}"
}
9567
+ 1085
= 10652
The parentheses let the equation span several lines: inside (…) and […], line breaks do not
end the statement.
You could also model the addition column by column, with a carry per column (each carry an
int[0..=1]). Both work; the single equation is shorter, and RedSAT’s exact arithmetic makes
it safe.
Grid puzzles
Grids are arrays of arrays, and loops over rows, columns and boxes generate the rules.
Sudoku
The puzzle. Fill a 9×9 grid with digits so that every row, every column and every 3×3 box contains each digit from 1 to 9 exactly once. Some cells are given.
The model. The grid is a 9×9 array of digits. The given cells are known and the empty ones
are ?, an anonymous unknown whose type (int[1..=9]) comes from the declaration. Then one
all_different per row, column and box does the rest:
var grid: [[int[1..=9]; 9]; 9] = [
[5, 3, ?, ?, 7, ?, ?, ?, ?],
[6, ?, ?, 1, 9, 5, ?, ?, ?],
[?, 9, 8, ?, ?, ?, ?, 6, ?],
[8, ?, ?, ?, 6, ?, ?, ?, 3],
[4, ?, ?, 8, ?, 3, ?, ?, 1],
[7, ?, ?, ?, 2, ?, ?, ?, 6],
[?, 6, ?, ?, ?, ?, 2, 8, ?],
[?, ?, ?, 4, 1, 9, ?, ?, 5],
[?, ?, ?, ?, 8, ?, ?, 7, 9],
]
for i in 0..9 {
require all_different(grid[i]) // row i
require all_different([grid[r][i] for r in 0..9]) // column i
var top = i / 3 * 3 // box i
var left = i % 3 * 3
require all_different([grid[top + r][left + c] for r in 0..3 for c in 0..3])
}
solve unique grid {
for row in grid {
print row
}
}
[5, 3, 4, 6, 7, 8, 9, 1, 2]
[6, 7, 2, 1, 9, 5, 3, 4, 8]
[1, 9, 8, 3, 4, 2, 5, 6, 7]
[8, 5, 9, 7, 6, 1, 4, 2, 3]
[4, 2, 6, 8, 5, 3, 7, 9, 1]
[7, 1, 3, 9, 2, 4, 8, 5, 6]
[9, 6, 1, 5, 3, 7, 2, 8, 4]
[2, 8, 7, 4, 1, 9, 6, 3, 5]
[3, 4, 5, 2, 8, 6, 1, 7, 9]
A few things to notice:
topandleftare computed from the known loop variablei, so they are plain numbers. The comprehensions pick out exactly the right cells, and the solver never sees the arithmetic.solve uniquesolves the puzzle and proves that it has only one solution, which is what makes a Sudoku a good one. It takes a few milliseconds.- Nothing here is specific to 9×9. A 4×4 or 16×16 Sudoku needs only different numbers.
N-Queens
The puzzle. Place N queens on an N×N chessboard so that no two attack each other: no two
share a row, a column or a diagonal. On the standard 8×8 board, there are 92 ways.
The model. Every row holds exactly one queen, so each row’s queen is a single unknown: the
column it stands in. Rows are then different by construction. Columns must differ too, which is
an all_different. Two queens share a diagonal exactly when the distance between their columns
equals the distance between their rows:
var N = 8
var queen: [int[0..N]; N] // queen[r]: the column of row r's queen
require all_different(queen)
for r1 in 0..N {
for r2 in r1 + 1..N {
require abs(queen[r1] - queen[r2]) != r2 - r1
}
}
var count = 0
solve all queen {
count = count + 1
if count == 1 {
for r in 0..N {
print board_row(queen[r], N)
}
}
}
print "{N} queens can be placed in {count} ways"
// One row of the board, with a queen in column q.
fn board_row(q: int, n: int) -> string {
var line = ""
for c in 0..n {
line = line + (if c == q { "Q " } else { ". " })
}
return line
}
. . . Q . . . .
Q . . . . . . .
. . . . Q . . .
. . . . . . . Q
. . . . . Q . .
. . Q . . . . .
. . . . . . Q .
. Q . . . . . .
8 queens can be placed in 92 ways
N is an ordinary known value: the loops turn it into the right number of requirements.
int[0..N] uses the exclusive range, which is exactly the valid columns 0 to N - 1. The body
counts every solution but draws only the first, using a function that builds a string.
Magic squares
The puzzle. Arrange the numbers 1 to 9 in a 3×3 grid so that every row, every column and both diagonals add up to the same total. (That total must be 15: the numbers add up to 45, spread over three rows.)
The model. A 3×3 grid of numbers from 1 to 9, all different, and one sum per line:
var square: [[int[1..=9]; 3]; 3]
var total = 15
require all_different([square[r][c] for r in 0..3 for c in 0..3])
for i in 0..3 {
require sum(square[i]) == total // row i
require sum(square[r][i] for r in 0..3) == total // column i
}
require sum(square[i][i] for i in 0..3) == total // one diagonal
require sum(square[i][2 - i] for i in 0..3) == total // the other
var count = 0
solve all square {
count = count + 1
if count == 1 {
for row in square {
print row
}
}
}
print "{count} magic squares"
[4, 9, 2]
[3, 5, 7]
[8, 1, 6]
8 magic squares
There are 8, but they are really one: the rotations and reflections of the same square. The symmetry breaking recipe shows how to ask for just one of each.
Number puzzles
RedSAT’s integers are exact, so number puzzles can be stated just as a mathematician would state them.
Factoring: running multiplication backwards
The problem. A number is the product of two primes, and we want to find them. Multiplying is easy; going back from the product to its factors is hard. The security of RSA encryption rests on that being infeasible for very large numbers.
The model. Two unknowns whose product is n, excluding the trivial 1 × n:
var n = 4295229443 // = 65537 × 65539
var x, y
require x > 1 and y > 1 // rule out the trivial 1 × n
require x <= y // symmetry breaking: each pair once
require x * y == n
solve x, y {
print "{n} = {x} × {y}"
} else {
print "{n} is prime"
}
4295229443 = 65537 × 65539
Nothing mentions bits. From x > 1, y > 1 and x * y == n, RedSAT infers that neither factor
exceeds n / 2, and x <= y tightens x to at most √n. It then builds a multiplier circuit for
x * y, and the SAT solver runs it backwards: which inputs make it output n?
If n is prime, there is no solution, and that is a proof that n is prime:
var n = 1000003
var x, y
require x > 1 and y > 1
require x <= y
require x * y == n
solve x, y {
print "{n} = {x} × {y}"
} else {
print "{n} is prime"
}
1000003 is prime
Factoring is a good way to feel the limits of SAT solving: products of two 32-bit primes take a while, and products of two 64-bit primes are far out of reach. See Performance tips.
Pythagorean triples
The problem. Which right triangles have whole-number sides, a² + b² = c², with sides up
to 30?
The model. Three bounded unknowns and the equation. a < b lists each triangle once
instead of twice:
var limit = 30
var a, b, c: int[1..=limit]
require a < b
require a * a + b * b == c * c
var count = 0
solve all a, b, c {
count = count + 1
}
print "{count} triples with sides up to {limit}"
11 triples with sides up to 30
Sums of two squares
The problem. Which numbers up to 50 can be written as a sum of two squares, a² + b²? For
example, 5 = 1² + 2², but 3 cannot be written that way.
The model. a and b are witnesses: they only need to exist. Because only total is
listed after solve all, each total is reported once, however many pairs produce it:
var total: int[1..=50]
var a, b
require a * a + b * b == total
var found = 0
solve all total {
found = found + 1
}
print "{found} numbers up to 50 are sums of two squares"
24 numbers up to 50 are sums of two squares
a and b have no declared range at all. From a * a + b * b == total and total <= 50,
RedSAT infers that both lie between −7 and 7.
A digit puzzle
The problem. What is the smallest four-digit multiple of 7 whose digits add up to 30?
The model. One unknown number. The digit sum is computed the way you would compute it for a
known number, with a while loop that strips off one digit at a time. Because the loop’s
condition depends on the unknown, it needs a bound; a four-digit number needs four
iterations:
var n: int[1000..=9999]
var digit_sum = 0
var rest = n
while rest > 0 bound 4 {
digit_sum = digit_sum + rest % 10
rest = rest / 10
}
require digit_sum == 30
require n % 7 == 0
solve n minimize n
n = 4998
/ and % on unknowns are encoded as a fresh quotient and remainder that must satisfy
rest == 10 * quotient + remainder, so no division circuit is needed. (The standard library’s
digit_sum does the same job in one call.)
Bit patterns
The problem. Which 8-bit numbers have exactly four one bits, and bits that read the same in both directions?
The model. One uint<8> unknown, with the standard library’s bit and popcount:
var x: uint<8>
require all(bit(x, i) == bit(x, 7 - i) for i in 0..4)
require popcount(x, 8) == 4
solve all x {
print "{x}: {binary(x)}"
}
fn binary(x: int) -> string {
var digits = ""
for i in 0..8 {
digits = (if bit(x, i) == 1 { "1" } else { "0" }) + digits
}
return digits
}
60: 00111100
153: 10011001
165: 10100101
195: 11000011
90: 01011010
102: 01100110
The function binary runs in the solve body, on a known x, so it is ordinary code.
Graph colouring
The problem. Colour every region of a map so that regions sharing a border get different colours. With few colours this is hard in general, and many real problems are colouring in disguise: assigning exams to time slots so that no student has two at once, or frequencies to radio masts so that neighbours do not interfere.
Here is mainland Australia’s states and territories, plus Tasmania, with three colours:
WA ─ NT ─ QLD
╲ │ ╱ │
SA ── NSW
╲ │
VIC TAS (an island)
The model. An enum names the colours, and a struct describes a border between two regions, by their index. The unknowns are one colour per region; one requirement per border does the rest:
enum Color { Red, Green, Blue }
struct Border { a: int, b: int }
var regions = ["WA", "NT", "SA", "QLD", "NSW", "VIC", "TAS"]
var borders = [
Border(0, 1), Border(0, 2), Border(1, 2), Border(1, 3),
Border(2, 3), Border(2, 4), Border(2, 5), Border(3, 4), Border(4, 5),
]
var color: [Color; len(regions)]
for border in borders {
require color[border.a] != color[border.b]
}
require color[0] == Color.Red // break the symmetry between colours
solve color {
for i in 0..len(regions) {
print "{regions[i]}: {color[i]}"
}
}
WA: Red
NT: Green
SA: Blue
QLD: Red
NSW: Green
VIC: Red
TAS: Red
warning: `color[6]` is unconstrained: no requirement mentions it
--> main.rsat:10:5
|
10 | var color: [Color; len(regions)]
| ^^^^^
= note: any value in its domain is a solution, so the value shown is arbitrary
The data (regions and borders) is separate from the model (the loop over borders), so colouring another map means changing only the data.
Why fix the first colour?
The colours are interchangeable: swap every Red with every Green in an answer, and you get another valid answer. Fixing the colour of one region removes these “same answer in disguise” duplicates. Here is the difference it makes when counting:
enum Color { Red, Green, Blue }
struct Border { a: int, b: int }
var regions = ["WA", "NT", "SA", "QLD", "NSW", "VIC", "TAS"]
var borders = [
Border(0, 1), Border(0, 2), Border(1, 2), Border(1, 3),
Border(2, 3), Border(2, 4), Border(2, 5), Border(3, 4), Border(4, 5),
]
var color: [Color; len(regions)]
for border in borders {
require color[border.a] != color[border.b]
}
var count = 0
solve all color {
count = count + 1
}
print "{count} colourings"
require color[0] == Color.Red
count = 0
solve all color {
count = count + 1
}
print "{count} colourings with WA red"
18 colourings
6 colourings with WA red
warning: `color[6]` is unconstrained: no requirement mentions it
--> main.rsat:9:5
|
9 | var color: [Color; len(regions)]
| ^^^^^
= note: any value in its domain is a solution, so the value shown is arbitrary
warning: `color[6]` is unconstrained: no requirement mentions it
--> main.rsat:9:5
|
9 | var color: [Color; len(regions)]
| ^^^^^
= note: any value in its domain is a solution, so the value shown is arbitrary
(The second solve sees the first one’s requirements plus the new one: constraints
accumulate.) On a big map with no
solution, symmetry makes the solver prove the same thing many times over; breaking it can be the
difference between seconds and hours. Symmetry breaking has more on this.
Knapsack and other optimization problems
The problem. You are packing for a hike. Your backpack can carry at most 200 units of weight, and each item you could take has a weight and a value (how much you want it). Which items should you pack to get the most value without going over the limit?
The same pattern shows up everywhere: choosing projects within a budget, loading cargo, picking ads for a page, allocating servers.
The model. One yes/no unknown per item: is it packed? The total weight of the packed items is at most the capacity, and we maximize the total value of the packed items:
var names = ["map", "compass", "water", "sandwich", "glucose", "tin", "banana", "apple"]
var weight = [9, 13, 153, 50, 15, 68, 27, 39]
var value = [150, 35, 200, 160, 60, 45, 60, 40]
var capacity = 200
var n = len(names)
var take: [bool; n]
require sum(weight[i] for i in 0..n if take[i]) <= capacity
solve take maximize sum(value[i] for i in 0..n if take[i]) {
print "take: {[names[i] for i in 0..n if take[i]]}"
print "weight {sum(weight[i] for i in 0..n if take[i])} of {capacity}, value {sum(value[i] for i in 0..n if take[i])}"
}
take: ["map", "compass", "sandwich", "glucose", "tin", "banana"]
weight 182 of 200, value 510
The filter if take[i] depends on unknowns, and that is fine inside sum: each term becomes
“weight[i] if item i is taken, otherwise 0”. Inside the solve body, take is known, so the
same comprehensions there are ordinary computations, and the array comprehension
[names[i] for … if take[i]] is allowed.
Adding side conditions
Real selection problems come with strings attached, and each one is a single requirement. Say the water is not optional, a compass is useless without the map, and the tin and the banana don’t fit in the side pocket together:
var names = ["map", "compass", "water", "sandwich", "glucose", "tin", "banana", "apple"]
var weight = [9, 13, 153, 50, 15, 68, 27, 39]
var value = [150, 35, 200, 160, 60, 45, 60, 40]
var capacity = 200
var n = len(names)
var take: [bool; n]
require sum(weight[i] for i in 0..n if take[i]) <= capacity
require take[2] // the water is not optional
require take[1] implies take[0] // a compass is useless without the map
require not (take[5] and take[6]) // not both the tin and the banana
solve take maximize sum(value[i] for i in 0..n if take[i]) {
print "take: {[names[i] for i in 0..n if take[i]]}"
print "weight {sum(weight[i] for i in 0..n if take[i])} of {capacity}, value {sum(value[i] for i in 0..n if take[i])}"
}
take: ["map", "compass", "water", "glucose"]
weight 190 of 200, value 445
A few more conditions you will often need, all one-liners:
| Condition | Requirement |
|---|---|
| take at most 3 items | require at_most(3, take) |
| take exactly one of items 4, 5 and 6 | require exactly(1, [take[4], take[5], take[6]]) |
| item 3 needs item 7 | require take[3] implies take[7] |
| items 1 and 2 go together or not at all | require take[1] iff take[2] |
Making change
The Optimization chapter’s coin example is the same idea with numbers instead of yes/no choices: how many of each coin, minimizing the total count.
Scheduling
The problem. Five jobs must run on a single machine, one at a time. Each job takes a certain time and cannot start before its release time, and some jobs must wait until others are finished: you cannot test before you build. When should each job start so that everything is done as early as possible?
| Job | Duration | Earliest start | Must wait for |
|---|---|---|---|
| design | 3 | 0 | |
| build | 5 | 0 | design |
| test | 2 | 0 | build |
| docs | 2 | 1 | |
| ship | 1 | 0 | test, docs |
The model. A struct describes each job. The unknowns are the start times, bounded by a horizon: running every job back to back can never take longer than the sum of all durations. Three kinds of requirements follow:
- a job starts no earlier than its release time;
- two jobs on the same machine do not overlap: one of them ends before the other starts;
- a job that must wait starts after the other one ends.
The goal, the makespan, is the time the last job ends, and we minimize it:
struct Job { name: string, duration: int, release: int }
var jobs = [
Job("design", 3, 0), Job("build", 5, 0), Job("test", 2, 0),
Job("docs", 2, 1), Job("ship", 1, 0),
]
var after = [[0, 1], [1, 2], [2, 4], [3, 4]] // [a, b]: b starts after a ends
var n = len(jobs)
var horizon = sum(job.duration for job in jobs) + 1
var start: [int[0..=horizon]; n]
fn end(start: int, job: Job) -> int {
return start + job.duration
}
for i in 0..n {
require start[i] >= jobs[i].release
for j in i + 1..n {
// One machine: jobs i and j do not overlap.
require end(start[i], jobs[i]) <= start[j] or end(start[j], jobs[j]) <= start[i]
}
}
for pair in after {
require end(start[pair[0]], jobs[pair[0]]) <= start[pair[1]]
}
var makespan = max(end(start[i], jobs[i]) for i in 0..n)
solve start minimize makespan {
for i in 0..n {
print "{jobs[i].name}: {start[i]}–{end(start[i], jobs[i])}"
}
print "everything done at {makespan}"
}
design: 0–3
build: 3–8
test: 10–12
docs: 8–10
ship: 12–13
everything done at 13
Some things worth noticing:
- Known data, unknown decisions. The jobs, with their names and durations, are known
structs. The function
endworks on a known job and an unknown start time alike. - “Or” constraints. The no-overlap rule says “i before j, or j before i”. The solver picks the order; that choice is what makes scheduling hard.
- The makespan is a
max. Minimizing the largest end time pulls every job as early as the rules allow. With 13 time units of work in total, 13 is clearly optimal here.
To schedule on several machines, add an unknown machine per job (int[0..machines]), and only
require “no overlap” for jobs on the same machine:
require machine[i] == machine[j] implies (… or …).
Counting constraints
Many rules are about how many: exactly two people on duty, at most four shifts a week, at
least one vowel. RedSAT’s count and the standard library’s exactly, at_least, at_most
and count_of say these directly.
| You want | Write |
|---|---|
| how many conditions hold | count(conditions) |
exactly k of them hold | exactly(k, conditions) |
at least / at most k hold | at_least(k, conditions), at_most(k, conditions) |
| how many elements equal a value | count_of(xs, value) |
| none / all / some hold | not any(…), all(…), any(…) |
conditions is an array of booleans, which you can write inline as a comprehension:
count(x > 0 for x in xs).
A duty roster
The problem. Four people share a duty over a week. Every day, exactly two of them are on duty. Everyone works three or four days, and nobody works three days in a row. Ann is away on Monday, and Ben has asked to work the weekend. Who works when?
The model. A grid of yes/no unknowns, one per person and day. Each rule becomes a counting requirement over a row or a column of the grid:
var people = ["Ann", "Ben", "Cleo", "Dev"]
var days = ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"]
var P = len(people)
var D = len(days)
var on: [[bool; D]; P] // on[p][d]: person p works on day d
// Two people every day.
for d in 0..D {
require exactly(2, [on[p][d] for p in 0..P])
}
for p in 0..P {
// Three or four days each, and never three days in a row.
require at_least(3, on[p]) and at_most(4, on[p])
for d in 0..D - 2 {
require not (on[p][d] and on[p][d + 1] and on[p][d + 2])
}
}
require not on[0][0] // Ann is away on Monday
require on[1][5] and on[1][6] // Ben works the weekend
solve on {
print " Mo Tu We Th Fr Sa Su"
for p in 0..P {
var line = people[p]
while len(line) < 6 {
line = line + " "
}
for d in 0..D {
line = line + (if on[p][d] { "X " } else { ". " })
}
print "{line}({count(on[p])} days)"
}
}
Mo Tu We Th Fr Sa Su
Ann . X X . X X . (4 days)
Ben X X . . . X X (4 days)
Cleo X . X X . . . (3 days)
Dev . . . X X . X (3 days)
The body pads names with a while loop. That loop’s condition is known (inside a body,
everything is), so it needs no bound.
How counting is encoded
count adds up its conditions, each worth 0 or 1, with a balanced tree of adders, so the sum
of n conditions needs only about log2(n) bits. exactly(k, …) is just count(…) == k, and
you can write that yourself whenever it reads better.
Counting also works on characters in strings. Which four-letter words over a, b and c
contain exactly two as, and never two equal letters in a row?
var w: string[4..=4]
require all(c in 'a'..='c' for c in w)
require count_char(w, 'a') == 2
require all(w[i] != w[i + 1] for i in 0..3)
solve all w
w = "baba"
w = "caba"
w = "acba"
w = "caca"
w = "baca"
w = "abca"
w = "acac"
w = "acab"
w = "abab"
w = "abac"
Symmetry breaking
Many problems have answers that are “the same in disguise”: swap two interchangeable things and you get another answer that is not really new. Colours in a map, identical machines, teams with no names, the rotations of a magic square.
Symmetric answers cost you twice:
- Enumeration repeats itself.
solve alllists every disguise separately. - Proofs repeat themselves. When there is no answer, or when proving an answer optimal, the solver may have to rule out each disguise of every dead end separately.
Symmetry breaking adds requirements that keep (at least) one representative of every group of symmetric answers, and rule out the rest.
Ordering interchangeable unknowns
When two unknowns play interchangeable roles, require them to be in order. This is why the
factoring example says require x <= y: without it, every factorization would be found twice,
as x × y and y × x.
var x, y: int[2..=50]
require x * y == 60
var count = 0
solve all x, y {
count = count + 1
}
print "{count} ordered pairs"
require x <= y
count = 0
solve all x, y {
count = count + 1
}
print "{count} pairs once we require x <= y"
10 ordered pairs
5 pairs once we require x <= y
Ordering interchangeable arrays: lex_less
When the interchangeable things are arrays, order them lexicographically, like words in a
dictionary. The standard library’s lex_less(xs, ys) holds when xs comes before ys.
The problem. Find four 5-bit codewords that differ pairwise in at least 3 positions, so that any single flipped bit can be detected and corrected. (Error-correcting codes like this protect data on disks and in transmission.)
The four codewords are interchangeable: any reordering of an answer is another answer. Requiring
code[0] < code[1] < code[2] < code[3] in dictionary order keeps exactly one ordering of each
set:
var N = 4
var code: [[int[0..=1]; 5]; N]
fn distance(a: [int], b: [int]) -> int {
return count(a[i] != b[i] for i in 0..len(a))
}
for i in 0..N {
for j in i + 1..N {
require distance(code[i], code[j]) >= 3
}
}
for i in 1..N {
require lex_less(code[i - 1], code[i]) // symmetry breaking
}
var count = 0
solve all code {
count = count + 1
}
print "{count} codes"
120 codes
Without the lex_less loop, the same program finds 2880 answers, 4! = 24 times as many, and
takes much longer to list them. lex_less_eq is the variant that allows equal arrays.
Fixing one choice
When values, rather than variables, are interchangeable (like colours), fix one choice: give the first region the first colour. The graph colouring recipe shows this, cutting 18 colourings down to 6. To go further, require that the second region uses one of the first two colours, and so on.
Rotations and reflections
The 8 magic squares from Grid puzzles are the rotations and reflections of a single square. A classic way to keep one of each: require that the top-left corner is the smallest corner, and that the top-right corner is smaller than the bottom-left one.
var square: [[int[1..=9]; 3]; 3]
var total = 15
require all_different([square[r][c] for r in 0..3 for c in 0..3])
for i in 0..3 {
require sum(square[i]) == total
require sum(square[r][i] for r in 0..3) == total
}
require sum(square[i][i] for i in 0..3) == total
require sum(square[i][2 - i] for i in 0..3) == total
// Symmetry breaking: one square per group of rotations and reflections.
var corners = [square[0][0], square[0][2], square[2][0], square[2][2]]
require all(square[0][0] <= c for c in corners)
require square[0][2] < square[2][0]
solve all square {
for row in square {
print row
}
}
[2, 9, 4]
[7, 5, 3]
[6, 1, 8]
Rotating moves another corner to the top left, and reflecting along the main diagonal swaps the top-right and bottom-left corners, so each of the 8 disguises fails one of the two rules except one.
A word of caution
Symmetry-breaking requirements must keep at least one answer from every group, or you lose answers. Add them only for symmetries you are sure of, and test them on a small instance by comparing counts with and without.
Lexical structure
How the text of a RedSAT program is split into words, numbers and symbols.
Source files
A program is a UTF-8 text file, conventionally with the extension .rsat. Non-ASCII characters
may appear in strings, characters and comments, but not in names.
Comments
// A line comment runs to the end of the line.
print 1 /* a block comment can sit inside a line */ + 2
/* Block comments
can span lines. */
3
Block comments do not nest: a block comment ends at the first */.
Statements and line breaks
A statement ends at the end of its line, or at a ;, which separates statements on one line:
var a = 1; var b = 2; print a + b
3
Line breaks inside parentheses (…) and square brackets […] are ignored, so a long expression
can continue on the next line when it is wrapped in parentheses, and a list can be written one
element per line, with an optional trailing comma:
var total = (1 + 2
+ 3 + 4)
var primes = [
2, 3, 5,
7, 11,
]
print total, primes
10 [2, 3, 5, 7, 11]
Braces {…} delimit blocks, whose statements end at line breaks as usual.
Names
A name starts with an ASCII letter or _, followed by letters, digits and _: x, queen,
max_weight, _tmp2. Names are case-sensitive.
Keywords
These words are reserved and can never be used as names:
| Kind | Keywords |
|---|---|
| declarations | var, fn, enum, struct, import |
| statements | require, solve, print, return |
| control flow | if, else, for, in, while |
| logical operators | and, or, not, xor, implies, iff |
| literals | true, false |
These words are keywords only in one position, and ordinary names everywhere else:
| Word | Keyword in |
|---|---|
all | solve all … |
unique | solve unique … |
limit | solve … limit K |
minimize | solve … minimize e |
maximize | solve … maximize e |
bound | while cond bound K { … } |
So var limit = 30 is fine, and all(…) is still the built-in function.
The built-in type names (bool, int, uint, char, string) and the names of the
built-in functions cannot be used to name functions, enums or structs.
Literals
| Literal | Examples | Notes |
|---|---|---|
| integer | 42, 1_000_000, 0xFF, 0b1010 | decimal, hexadecimal or binary; _ separates digits; any size |
| boolean | true, false | |
| character | 'a', '7', '\n', '\'' | exactly one character, or an escape |
| string | "hello", "x = {x}" | on one line; {…} interpolates an expression |
| hole | ? | an anonymous unknown (see Types) |
There are no negative literals: -5 is the unary minus applied to 5, which comes to the same.
The escapes, in characters and strings, are:
| Escape | Means |
|---|---|
\n | line feed |
\t | tab |
\r | carriage return |
\0 | the null character |
\\ | a backslash |
\" | a double quote |
\' | a single quote |
\{ | a literal { |
\} | a literal } |
var x = 0xFF_FF + 0b1010 + 1_000
print x, "x is {x}", 'q', "a \{literal\} brace"
66545 x is 66545 q a {literal} brace
Operators and punctuation
+ - * / % ^ arithmetic
== != < <= > >= comparison
& | << >> bitwise (and the keyword xor)
.. ..= ranges
= assignment
-> function result type
. field access, enum variants
, : ; ? separators, type annotations, statement separator, hole
( ) [ ] { } grouping, arrays and indexing, blocks
&&, || and ! are not RedSAT operators: the compiler suggests and, or and not (or
!=) instead.
Statements
A program is a sequence of statements, run from top to bottom. Declarations of functions, enums and structs are the exception: they apply to the whole file, wherever they appear.
var x, y: T declare unknowns (or, with "= e", a defined value)
x = e assign (also a[i] = e, p.f = e)
require e every answer must satisfy e
print e1, e2, … print values
solve … find answers (see below)
if c { … } else { … } branch
for x in r { … } loop over a range, array or string
while c bound K { … } loop ("bound K" when c depends on unknowns)
fn f(p: T, …) -> T { … } declare a function
return e return from a function
enum E { A, B } declare an enum
struct S { f: T, … } declare a struct
import "file.rsat" bring in another file's declarations
f(…) call a function for its effects
var
var x // an unknown; its type is inferred from its use below
var a, b: int[0..=9] // several unknowns of one type
var n = 42 // a defined value (known here)
var m: int[0..=100] = n // a defined value with a type, which it must fit
require x == a + b
print n, m
42 42
- Without
= e, each declared name is a fresh unknown of the given (or inferred) type. An unknown array or string needs a type with a length. - With
= e, the variable is defined bye: known ifeis, otherwise derived from unknowns. Only a single variable can have an initial value. - With both a type and
= e, the value must fit the type: a known value outside the range is an error, and an unknown one is required to fit. - A name can be declared only once per block. An inner block may declare a name again, hiding the outer one until the block ends.
Assignment
place = e gives a variable a new value. The place may be a variable, an array element or a
field, nested as deep as needed: grid[r][c] = 0, jobs[i].start = 3. Each assignment creates a
new version of the variable; requirements made earlier keep referring to the earlier version.
An array index in an assignment may be unknown: slots[k] = 7 writes 7 into whichever element
k selects. Strings cannot be changed in place, and a loop variable cannot be assigned to.
require
require e adds the requirement that e, a bool, holds in every answer. Inside an if
whose condition c depends on unknowns, it means c implies e. Not allowed inside a solve
body.
print
print e1, e2, … prints its arguments separated by spaces, then a line break (print alone
prints an empty line). Strings and characters print without quotes at the top level and with
quotes inside arrays; enums print as their variant name; structs as Name(field: value, …).
Every printed value must be known, so outside solve bodies you cannot print unknowns, nor
print under a condition that depends on unknowns.
solve
solve [all | unique] [e1, e2, …] [limit K] [minimize e | maximize e] [{ body }] [else { body }]
| Part | Meaning |
|---|---|
e1, e2, … | what to show; two answers differ when one of these differs. Default: every variable that depends on unknowns |
| (no mode) | the first answer (or the first K with limit K) |
all | every answer (at most K with limit K) |
unique | the answer, and a proof that it is the only one; an error if there are more. Cannot have a limit |
limit K | at most K answers; K is a known positive number |
minimize e | an answer with the smallest value of e; with all, every such answer |
maximize e | an answer with the largest value of e; with all, every such answer |
{ body } | runs once per answer, with every unknown known; without a body, the listed expressions are printed as e = value, … |
else { body } | runs when there is no answer; otherwise no solution and an explanation are printed |
Each solve takes into account every requirement made before it in the program. solve must
be at the top level: not inside a function, nor under a condition that depends on unknowns. A
solve body cannot contain require or another solve, but it can assign to variables declared
outside it.
if
if condition { … } else if condition { … } else { … }
When the condition is known, only the branch taken runs. When it depends on unknowns, every branch runs under its condition, and each variable assigned in a branch ends up as “the value from the branch whose condition holds”. See Control flow over unknowns.
for
for name in lo..hi { … } for name in lo..=hi { … }
for name in array { … } for name in string { … }
The range bounds must be known, and so must the length of an array. A string of unknown length
is looped over up to its maximum length, each iteration guarded by “this position exists”. The
loop is unrolled: the body runs once per element, with name bound to it. At most ten million
iterations are allowed.
while
while condition { … }
while condition bound K { … }
While the condition is known, the loop runs as usual, up to ten million iterations. Once the
condition depends on unknowns, bound K (a known, non-negative number) is required: the loop
runs at most K times in total, each iteration guarded by the condition, and the loop is
required to have finished after the last one.
fn and return
fn name(param: Type, …) -> ResultType { … }
fn name(param: Type, …) { … }
Declares a function, at the top level only. Every parameter needs a type; array parameters may
leave out the length (xs: [int]). Without -> ResultType, the function returns nothing and is
called as a statement. Functions only see their parameters and their own variables.
return e (or a bare return in a function without a result) leaves the function, also under
conditions that depend on unknowns. A function with a result type must return on every path.
Calls are inlined, nested at most 200 deep. A user function shadows a standard library function of the same name. See Functions.
enum and struct
enum Name { Variant1, Variant2, … }
struct Name { field1: Type, field2: Type, … }
Declared at the top level only. Variants and fields are separated by commas or line breaks.
Variants are written Name.Variant; struct values are built with Name(v1, v2) or
Name(field1: v1, field2: v2), all positional or all named. See Types.
import
import "relative/path.rsat"
At the top level only. Loads the functions, enums and structs declared in another file, which may contain nothing else (and further imports). Paths are relative to the importing file; each file is loaded once. See Imports.
Call statements
A function call on its own line, such as ascending(digits), calls the function for its effects
(typically, the requirements it adds). Any other expression on its own line is an error: write
require … or print ….
Types
| Type | Values | Encoded as |
|---|---|---|
bool | true, false | one SAT variable |
int | any integer; the range is inferred | two’s complement, sized to fit |
int[lo..hi] | integers from lo up to, but excluding, hi | sized to the range |
int[lo..=hi] | integers from lo up to and including hi | sized to the range |
uint<N> | 0 to 2^N − 1 | N bits |
int<N> | −2^(N−1) to 2^(N−1) − 1 | N bits |
char | a Unicode character, such as 'a' | its code, sized to fit |
string | a sequence of characters, of bounded length | characters plus a length |
string[lo..hi], string[lo..=hi] | strings whose length is in the range | characters plus a length |
[T; N] | exactly N values of type T | N encoded elements |
[T] | an array of any length (parameters and known values only) | |
Name (an enum) | one of the enum’s variants | a small integer |
Name (a struct) | a record with the struct’s fields | its fields |
All bounds (lo, hi, N) can be any expression that is known when the program runs, such as
int[0..N] or [bool; len(names)].
Integers
Integers are mathematical integers. Arithmetic on them is exact: every intermediate result gets as many bits as its value can need, so there is no overflow and no wraparound.
A type’s bounds restrict the values a variable may take, not the arithmetic done with it:
with a, b: uint<8>, a + b may be 510. Storing a value into a variable with a bounded type,
var c: uint<8> = a + b, requires the value to fit.
- Ranges.
lo..hiexcludeshiandlo..=hiincludes it, soint[0..10]andint[0..=9]are the same type. A range with no values (int[5..5]) is an error. - Fixed widths. In
int<N>anduint<N>,Nis between 1 and 65536.uintalways needs a width;intwithout one is the unboundedint. - Inference. The range of a plain
intunknown is inferred from the requirements that apply unconditionally (those not under a condition that depends on unknowns). An explicit range always takes precedence: inference may narrow it, never widen it. - Unbounded integers. If no finite range can be inferred, RedSAT warns and searches with
growing magnitudes (
|x| < 2^32,2^64, …, up tomax-int-bits), or reports an error ifunbounded-ints = "error". See Configuration.
Booleans
true and false. Booleans are not integers: flag + 1 is a type error. To count booleans, use
count.
Characters
A char is a Unicode scalar value, written 'a', '7' or '\n'. Characters can be compared
with == != < <= > >= (by their code), tested with in against a range of characters
(c in 'a'..='z') or a string (c in "aeiou"), and converted with ord(c) (the code) and
chr(n) (the character with code n).
An unconstrained unknown char can be any Unicode character, not only a printable one, so give
character unknowns a range when you print them.
Strings
A string is a sequence of characters. Known strings support len(s), s[i] (a char),
s + t, reverse(s), ==, !=, c in s and for c in s.
An unknown string has an unknown length within its declared range, and an unknown character in
every position up to its capacity, the largest length allowed: string[2..=5] holds 2 to 5
characters. A plain string unknown has capacity 32, with a warning. Positions beyond a string’s
length are unused, so two strings are equal exactly when their lengths and their characters
agree.
The same operations work on unknown strings: len(w) is an unknown integer, w[i] requires i
to be within the length, and + joins strings of unknown lengths. Strings cannot be changed in
place: s[0] = 'x' is an error.
Arrays
[T; N] holds exactly N elements of type T, where N is known; arrays nest, as in
[[int[1..=9]; 9]; 9]. Array values are written [1, 2, 3] or with a comprehension
[x * x for x in 1..=5]. Elements are read and written as xs[i], and the index may be unknown,
which requires it to be in range. len(xs) is always known.
Arrays support ==, !=, + (concatenation), x in xs, for x in xs, reverse, and the
aggregates (sum, count, all, any, min, max, all_different).
[T], without a length, is the type of an array parameter that accepts arrays of any length. A
known array may also be annotated with it.
Holes
? stands for a fresh, anonymous unknown of whatever type the context expects. It lets a value
mix known and unknown parts:
struct Point { x: int[0..=5], y: int[0..=5] }
var p = Point(1, ?) // x is known, y is not
var row: [int[1..=4]; 4] = [1, ?, ?, 4] // two known cells, two unknown ones
require p.y == p.x + 2 and all_different(row) and row[1] < row[2]
solve p, row
p = Point(x: 1, y: 3), row = [1, 2, 3, 4]
A ? stands for a single value (a number, a boolean, a character, an enum or a struct), not a
whole array, and its type must be clear from the context.
Enums
enum Suit { Hearts, Diamonds, Clubs, Spades }
var s: Suit
require s != Suit.Hearts and s != Suit.Spades
solve all s
print Suit.Clubs == Suit.Clubs
s = Diamonds
s = Clubs
true
Variants are written Name.Variant and compared with == and != only. An enum needs at least
one variant, and variants must be distinct.
Structs
struct Card { rank: int[1..=13], suit: int[0..4] }
var hand: [Card; 2]
require hand[0].rank + hand[1].rank == 3 and hand[0].rank < hand[1].rank
require hand[0].suit == hand[1].suit + 1
solve hand
var c = Card(rank: 12, suit: 0)
c.rank = 13
print c, c == Card(13, 0)
hand = [Card(rank: 1, suit: 3), Card(rank: 2, suit: 2)]
Card(rank: 13, suit: 0) true
Struct values are built with the struct’s name, with all arguments positional
(Card(13, 0)) or all named (Card(rank: 13, suit: 0)). Fields are read and assigned as
c.rank. Structs compare with == and !=, field by field.
Type inference
Every expression has a type, worked out by the type checker before the program runs.
- A variable with an initial value takes its type from it (
var n = 42is anint). - A variable without one takes its type from its annotation or, failing that, from its uses:
var xused inx * 2is anint, used inx and yabool. - If no use settles it, the program is rejected with “cannot infer the type”, asking for an annotation.
- With the compiler option
explicit-types = "unknowns"(or"all"), annotations are required. See Configuration.
Equality (==, !=) is defined for every type; the order comparisons (<, …) for integers and
characters only.
Expressions and operators
Every operator works on known values and on unknowns, with the same meaning. A few operands must be known, as noted below.
Precedence
From loosest to tightest binding:
| Operators | Associativity |
|---|---|
iff | left |
implies | right |
or | left |
xor | left |
and | left |
not | prefix |
== != < <= > >= in | none: cannot chain |
| (bitwise or) | left |
& (bitwise and) | left |
<< >> | left |
+ - | left |
* / % | left |
- (negation) | prefix |
^ (power) | right |
f(…) a[i] p.x E.V | postfix |
Some consequences:
print 1 + 2 * 3 ^ 2 // 1 + (2 * (3 ^ 2))
print -2 ^ 2, 2 ^ 3 ^ 2 // -(2 ^ 2) and 2 ^ (3 ^ 2)
print 6 & 3 == 2 // (6 & 3) == 2: bitwise binds tighter than ==
print not 1 == 2 // not (1 == 2)
print true or false and false // true or (false and false)
print false implies false implies false // false implies (false implies false)
19
-4 512
true
true
true
true
Arithmetic
| Expression | Operands | Result | Notes |
|---|---|---|---|
a + b | int | int | exact |
a - b | int | int | exact |
a * b | int | int | exact |
a / b | int | int | Euclidean division (see below) |
a % b | int | int | Euclidean remainder: always in 0..abs(b) |
a ^ b | int | int | b must be known and non-negative; at most 64 when a is unknown |
-a | int | int |
Integers never overflow: every result is exact, whatever its size.
Euclidean division. a / b and a % b satisfy a == (a / b) * b + a % b with
0 <= a % b < abs(b). For positive operands this is ordinary integer division; for negative ones
it differs from C, Java or Rust:
a | b | a / b | a % b |
|---|---|---|---|
| 7 | 2 | 3 | 1 |
| -7 | 2 | -4 | 1 |
| 7 | -2 | -3 | 1 |
| -7 | -2 | 4 | 1 |
Division by zero. Dividing a known value by zero is an error. Dividing by an unknown adds the
requirement that it is not zero. In a branch that may not be taken (if d != 0 { n / d } else { 0 }),
the division is guarded like everything else in that branch.
Comparison
| Expression | Operands | Result |
|---|---|---|
a == b, a != b | any two values of the same type | bool |
a < b, a <= b, a > b, a >= b | int or char | bool |
Comparisons do not chain: write a < b and b < c, or b in a + 1..c.
Logic
| Expression | Operands | True when |
|---|---|---|
not a | bool | a is false |
a and b | bool | both are true |
a or b | bool | at least one is true |
a xor b | bool | exactly one is true |
a implies b | bool | a is false or b is true |
a iff b | bool | both have the same value |
and, or and implies evaluate b only where it matters: if a decides the result, b is
not evaluated at all, and if a is unknown, b is evaluated under the condition that it
matters (a for and and implies, not a for or). Requirements that b brings along,
such as an index being in range, then only apply under that condition.
Bitwise operators
| Expression | Operands | Result | Notes |
|---|---|---|---|
a & b | int | int | bitwise and |
a | b | int | int | bitwise or |
a xor b | int | int | bitwise exclusive or |
a << k | int | int | a * 2^k; k must be known and non-negative |
a >> k | int | int | a / 2^k, rounding down; k must be known and non-negative |
Bitwise operators act on the two’s-complement representation, as if integers had infinitely
many bits: -5 & 3 == 3, -5 | 3 == -5, -5 xor 3 == -8.
Membership: in
| Expression | True when |
|---|---|
x in lo..hi | lo <= x and x < hi (x an int or a char) |
x in lo..=hi | lo <= x and x <= hi |
x in array | some element equals x |
c in string | the character c occurs in the string |
Ranges
lo..hi (excluding hi) and lo..=hi (including it) are not values of their own: they appear
in types (int[0..10]), loops (for i in 0..n), comprehensions and in.
Indexing and fields
xs[i]reads elementi(counting from 0) of an array or string. The index may be unknown: that requires it to be in range.p.freads fieldfof a struct.E.Vis variantVof enumE.
A known index out of range is an error.
if expressions
if condition { value1 } else { value2 }
if c1 { v1 } else if c2 { v2 } else { v3 }
Both branches are required and must have the same type. With an unknown condition, the result is
value1 where the condition holds and value2 elsewhere, and each branch is evaluated under its
condition.
Comprehensions
[element for x in iterable]
[element for x in iterable if condition for y in iterable if condition …]
Builds an array by looping, with any number of for clauses (nested from left to right), each
followed by any number of if filters. An array comprehension’s filters must be known, because
the array’s length must be.
The same clauses can be written directly inside the call of an aggregate, or of a function whose
only parameter is an array: sum(w[i] for i in 0..n if take[i]). Inside sum, count, all
and any, filters may depend on unknowns: a filtered-out element contributes 0 to sum and
count, true to all and false to any.
Strings
"text {expression} text" inserts the value of each {expression}, which may be any expression
without braces or string literals of its own. Inserted values are shown as print shows them.
Write \{ and \} for literal braces.
a + b joins two strings, or two arrays.
Function calls
name(argument, …) calls a built-in, standard library or user function, with positional
arguments. Name(…) with a struct’s name builds a struct, with positional or named arguments.
See Built-in functions and Standard library.
Holes
? is an expression that stands for a fresh unknown of the type the context expects. See
Types.
Built-in functions
These functions are part of the language. All of them work on known values and on unknowns. On top of them, the standard library adds many more, written in RedSAT.
| Function | Result | Meaning |
|---|---|---|
abs(x) | int | the absolute value of x |
isqrt(n) | int | √n rounded down: the largest r with r * r <= n |
min(a, b, …), min(xs) | int | the smallest of the arguments, or of the elements of xs |
max(a, b, …), max(xs) | int | the largest of the arguments, or of the elements of xs |
len(xs) | int | the length of an array or a string |
sum(xs) | int | the sum of the elements (0 for none) |
count(bs) | int | how many elements are true |
all(bs) | bool | every element is true (true for none) |
any(bs) | bool | at least one element is true (false for none) |
all_different(xs) | bool | no two elements of the array are equal |
reverse(xs) | array or string | the array or string, back to front |
ord(c) | int | the code of character c |
chr(n) | char | the character with code n |
print abs(-7), abs(7)
print isqrt(10), isqrt(16), isqrt(10 ^ 100) == 10 ^ 50
print min(3, 1, 2), max(3, 1, 2), min([5, 9]), max(x % 7 for x in 10..20)
print len([1, 2, 3]), len("hello"), len([[1], [2, 3]])
print sum([1, 2, 3]), sum(x for x in 1..=100 if x % 3 == 0), sum([])
print count([true, false, true]), count(x > 2 for x in [1, 5, 9])
print all([true, true]), all([]), any([false]), any([])
print all_different([1, 2, 3]), all_different(["a", "b", "a"])
print reverse([1, 2, 3]), reverse("stressed")
print ord('A'), chr(97), chr(ord('a') + 25)
7 7
3 4 true
1 3 5 6
3 5 2
6 1683 0
2 2
true true false false
true false
[3, 2, 1] desserts
65 a z
Integer square root
isqrt(n) is √n rounded down; n must not be negative. With a known n, it is computed exactly
while the program compiles, however large n is, so it costs the solver nothing: use it to
bound a search, such as the smaller factor of a number (require x <= isqrt(n)). With an
unknown n, the result is an unknown that the solver keeps equal to √n rounded down, and n
is required not to be negative:
var n: int[0..=100]
require isqrt(n) == 5 and n % 2 == 0
solve n maximize n
n = 34
Aggregates and comprehensions
min, max, len, sum, count, all, any, all_different and reverse take one array,
which can be written as a comprehension directly inside the parentheses:
var take: [bool; 4]
var weight = [3, 5, 2, 7]
require count(take) == 2
require sum(weight[i] for i in 0..4 if take[i]) == 9
solve all take
take = [false, false, true, true]
In sum, count, all, any, len and all_different, a filter (if …) may depend on
unknowns. An element that is filtered out counts as 0 for sum and count, as true for all
and as false for any; len counts the elements that pass, and all_different requires the
elements that pass to differ. In min, max and reverse, filters must be known, since the
elements taking part must be.
var v = [1, 1, 2]
var pick: [bool; 3]
require all_different(v[i] for i in 0..3 if pick[i]) // the picked values differ
require len(i for i in 0..3 if pick[i]) == 2 // two are picked
solve all pick
pick = [true, false, true]
pick = [false, true, true]
Notes
minandmaxwith several arguments compare those arguments; with one, it must be an array (min(3)is an error). The array must not be empty.lenof an array is always known. Of an unknown string, it is an unknown integer.sumandcountadd their terms with a balanced tree of adders, so the result needs only a few more bits than the largest term.all_differentworks on arrays of integers, booleans, characters, strings, enums and structs. It is encoded as “every pair differs”.reverseof an unknown string reverses its firstlen(s)characters.ordandchrconvert between characters and their Unicode code points.chrof a known number that is not a valid code point is an error; on an unknown number, it requires a valid one.
These names cannot be used for your own functions, enums or structs. (They can still be used as variable names, although that is rarely a good idea.)
Standard library
The standard library (the prelude) is available in every program, without an import. It is
written in RedSAT itself: every function is an ordinary RedSAT function, inlined at each call
like your own, so it works on known values and on unknowns alike. Its source is
crates/redsat-lang/src/prelude.rsat, and reading it is a good way to learn idiomatic RedSAT.
If you declare a function with the same name, yours is used instead, everywhere (see Functions).
Some parameters must be known when the function is called, because they set a loop range, an array length or a shift amount; the tables below say which.
Numbers
| Function | Description |
|---|---|
sign(x: int) -> int | −1, 0 or 1: the sign of x. |
clamp(x: int, lo: int, hi: int) -> int | x, limited to the range lo..=hi. |
divides(d: int, n: int) -> bool | Whether d divides n. d must not be 0. |
is_even(x: int) -> bool | Whether x is even. |
is_odd(x: int) -> bool | Whether x is odd (also for negative x). |
gcd(a: int, b: int) -> int | The greatest common divisor. Both arguments must be known. |
digits(n: int, k: int) -> [int] | The k decimal digits of n, most significant first, with leading zeros. n is non-negative with at most k digits; k must be known. |
digit_sum(n: int, k: int) -> int | The sum of the k decimal digits of n; k must be known. |
bit(x: int, i: int) -> int | Bit i of x (two’s complement): 0 or 1. i must be known. |
popcount(x: int, width: int) -> int | The number of one bits among the lowest width bits of x; width must be known. |
print sign(-5), sign(0), sign(7)
print clamp(15, 0, 10), clamp(-3, 0, 10), clamp(4, 0, 10)
print divides(3, 12), divides(5, 12), is_even(-4), is_odd(-3)
print gcd(84, 36), digits(4096, 4), digits(42, 4), digit_sum(4096, 4)
print bit(6, 0), bit(6, 1), bit(-1, 100), popcount(255, 8), popcount(-1, 4)
-1 0 1
10 0 4
true false true true
12 [4, 0, 9, 6] [0, 0, 4, 2] 19
0 1 1 8 4
On unknowns: which three-digit odd multiple of 7 has digits adding up to 25?
var n: int[100..=999]
require digit_sum(n, 3) == 25 and is_odd(n) and divides(7, n)
solve all n
n = 889
Counting
| Function | Description |
|---|---|
exactly(k: int, conditions: [bool]) -> bool | Whether exactly k of the conditions hold. |
at_least(k: int, conditions: [bool]) -> bool | Whether at least k of the conditions hold. |
at_most(k: int, conditions: [bool]) -> bool | Whether at most k of the conditions hold. |
count_of(xs: [int], value: int) -> int | How many elements of xs equal value. |
var flags = [true, false, true, true]
print exactly(3, flags), at_least(4, flags), at_most(3, flags)
print count_of([1, 2, 1, 3], 1)
true false true
2
The counting constraints recipe uses these to build a duty roster.
Arrays
| Function | Description |
|---|---|
product(xs: [int]) -> int | The product of the elements (1 for none). |
all_equal(xs: [int]) -> bool | Whether all elements are equal. |
increasing(xs: [int]) -> bool | Whether each element is at most the next one. |
strictly_increasing(xs: [int]) -> bool | Whether each element is smaller than the next one. |
decreasing(xs: [int]) -> bool | Whether each element is at least the next one. |
strictly_decreasing(xs: [int]) -> bool | Whether each element is larger than the next one. |
all_different_except(xs: [int], ignored: int) -> bool | Whether no two elements are equal, except for copies of ignored (e.g. 0 for “empty”). |
index_of(xs: [int], value: int) -> int | The first position of value in xs, or −1. |
lex_less(xs: [int], ys: [int]) -> bool | Whether xs comes before ys in lexicographic (dictionary) order. Useful to break symmetries. |
lex_less_eq(xs: [int], ys: [int]) -> bool | Whether xs comes before ys in lexicographic order, or equals it. |
sorted(xs: [int]) -> [int] | The elements in increasing order. Built as a sorting network, so it works on unknown elements. |
is_permutation(xs: [int], ys: [int]) -> bool | Whether ys is a rearrangement of xs. |
print product([2, 3, 7]), all_equal([4, 4, 4])
print increasing([1, 2, 2]), strictly_increasing([1, 2, 2])
print decreasing([3, 2, 2]), strictly_decreasing([3, 2, 1])
print all_different_except([0, 1, 0, 2], 0), index_of([5, 7, 9, 7], 7), index_of([5, 7], 8)
print lex_less([1, 2], [1, 3]), lex_less([1, 3], [1, 3]), lex_less([1], [1, 0])
print lex_less_eq([1, 3], [1, 3]), sorted([3, 1, 2, 1])
print is_permutation([1, 2, 3], [3, 1, 2]), is_permutation([1, 2], [1, 1])
42 true
true false
true true
true 1 -1
true false true
true [1, 1, 2, 3]
true false
sorted on unknowns: which arrays of three digits sort to [2, 5, 7], with the first element
larger than the last?
var xs: [int[0..=9]; 3]
require sorted(xs) == [2, 5, 7] and xs[0] > xs[2]
solve all xs
xs = [7, 5, 2]
xs = [5, 7, 2]
xs = [7, 2, 5]
sorted uses an odd–even transposition network: about n²/2 compare-and-swap steps for n
elements, so it suits short arrays.
Characters and strings
| Function | Description |
|---|---|
is_digit(c: char) -> bool | Whether c is one of '0' … '9'. |
is_lower(c: char) -> bool | Whether c is one of 'a' … 'z'. |
is_upper(c: char) -> bool | Whether c is one of 'A' … 'Z'. |
is_letter(c: char) -> bool | Whether c is an ASCII letter. |
to_upper(c: char) -> char | c in upper case (ASCII letters only; others unchanged). |
to_lower(c: char) -> char | c in lower case (ASCII letters only; others unchanged). |
digit_value(c: char) -> int | The value of a digit character: '7' → 7. |
starts_with(s: string, prefix: string) -> bool | Whether s starts with prefix, whose length must be known. |
ends_with(s: string, suffix: string) -> bool | Whether s ends with suffix, whose length must be known. |
count_char(s: string, c: char) -> int | How many times c occurs in s. |
print is_digit('7'), is_lower('a'), is_upper('a'), is_letter('Z'), is_letter('?')
print to_upper('q'), to_lower('Q'), to_upper('!'), digit_value('8')
print starts_with("hello", "he"), ends_with("hello", "lo"), count_char("banana", 'a')
true true false true false
Q q ! 8
true true 3
On an unknown string: a word of 4 to 6 lowercase letters that starts with “ab”, ends with “ba”
and has three as:
var w: string[4..=6]
require all(is_lower(c) for c in w)
require starts_with(w, "ab") and ends_with(w, "ba") and count_char(w, 'a') == 3
solve w
w = "ababa"
Command line
redsat <FILE> [OPTIONS] run a program (the default action)
redsat check <FILE> [OPTIONS] parse and type-check a program, without running it
redsat repl [OPTIONS] build a program interactively
redsat dimacs <PATH> [--solver S] solve a CNF formula in DIMACS format
redsat lsp run the language server, for editors
redsat help [COMMAND] show help
redsat --help (or -h) and redsat <command> --help describe every option; redsat --version
(or -V) prints the version.
Running a program
$ redsat program.rsat [OPTIONS]
The program’s output (print and solutions) goes to standard output. Diagnostics (errors,
warnings and notes) go to standard error, after the program’s output, followed by the
statistics if --stats was given. The exit status is 0 when the program ran without errors,
and 1 otherwise. A solve without a solution is not an error.
| Option | Effect |
|---|---|
--stats | After the run, print statistics for every solve to standard error (see below). |
-v, --verbose | Report progress to standard error as it happens (see below). |
--interactive | Pause after each solution of every solve: Enter shows the next one, a (or all) all the remaining ones, and q (or quit) stops enumerating that solve. End of input counts as q. |
--solver <cadical|builtin> | The SAT solver: cadical (the default) or builtin, RedSAT’s own CDCL solver written in Rust. Both give correct answers; builtin is slower. |
-j, --threads <N> | How many threads may work on a hard SAT problem (default: the number of cores, at most 4). Differently configured solvers race and the first answer wins; easy problems are solved on one thread. solve all (without limit or an objective) instead splits the solutions among the threads, and reports them in a fixed order. With several threads, which of several valid solutions is found can vary from run to run: use -j 1 for reproducible output. |
It also accepts the compiler options below.
Compiler options
These override the settings of a redsat.toml file. They are accepted when
running a program, and by check and repl.
| Option | Effect |
|---|---|
--strict | Enable every strict check: explicit-types = "unknowns" and unbounded-ints = "error", unless set otherwise. |
--explicit-types <off|unknowns|all> | Which declarations need a type annotation. |
--unbounded-ints <deepen|error> | What to do with integers whose range cannot be inferred. |
--fallback-int-bits <BITS> | The first magnitude, in bits, tried for unbounded integers (default 32). |
--max-int-bits <BITS> | Stop widening unbounded integers beyond this many bits (default 256). |
--config <FILE> | Use this configuration file instead of searching for redsat.toml. |
redsat check
$ redsat check program.rsat
program.rsat: ok
Parses and type-checks the program and the files it imports, applying the compiler options,
without running it. Prints <file>: ok and exits with 0 when there are no errors; otherwise
prints the errors and exits with 1. Errors that only arise while the program runs (an index out
of range, a loop bound that depends on unknowns, …) are not detected.
redsat repl
Starts an interactive session; see The REPL. Accepts the compiler
options and --solver. It looks for a redsat.toml in the current directory and its parents.
redsat dimacs
$ cat problem.cnf
p cnf 3 2
1 -3 0
2 3 -1 0
$ redsat dimacs problem.cnf
s SATISFIABLE
v -1 -2 -3 0
Solves a raw CNF formula in DIMACS format, the standard input format of SAT solvers: a
p cnf <variables> <clauses> header, then one clause per line as a list of literals ending in
0 (-3 is “not variable 3”). It prints the answer in SAT Competition format: an s line with
SATISFIABLE or
UNSATISFIABLE, and for a satisfiable formula v lines with the value of every variable
(positive for true, negative for false), ending with 0. Use - as the path to read standard
input. The exit status follows the SAT solver convention: 10 for satisfiable, 20 for
unsatisfiable. --solver picks the solver, as when running programs.
redsat lsp
Runs the language server over standard input and output, as editors expect. See Editor support.
Reading --stats
$ redsat examples/factor.rsat --stats
4295229443 = 65537 × 65539
stats: solve at examples/factor.rsat:14
x: [34, 130158467] · 27 bits
y: [34, 130158467] · 27 bits
circuit: 5948 AND gates · CNF: 5832 variables, 16880 clauses
1 SAT call · 1 solution · 78.67ms (build 18.12ms, search 60.39ms)
For each solve, in order:
- the unknowns the
solvedepends on, each with the range RedSAT inferred for it and the number of bits that range needs; - the circuit size in AND gates, and the size of the CNF formula given to the solver;
- the number of SAT calls (one per answer, plus one to prove there are no more, plus the probes of an optimization), the number of solutions reported, and the time taken, split into build (ranges, circuit, CNF) and search (SAT solving and decoding).
When unbounded integers were involved, a line says which magnitude was searched.
Reading --verbose
--verbose prints the same kind of information, and more, while the program runs, each line
starting with [redsat]. Here is a Sudoku:
$ redsat examples/sudoku.rsat --verbose
[redsat] loaded 2 files (examples/sudoku.rsat, <prelude>) · parsed and checked in 513.12µs
[redsat] solve #1 at examples/sudoku.rsat:27
[redsat] model unique · 78 requirements · 242 IR terms
[redsat] unknowns 51 (51 integer, 0 boolean), 0 fixed by domain inference · domains in 34.40µs
[redsat] ?8:12: [1, 9] · 4 bits
[redsat] ?8:16: [1, 9] · 4 bits
[redsat] …
[redsat] … and 43 more
[redsat] space 204 decision bits → 2^204 candidate assignments
[redsat] circuit 6502 AND gates over 204 inputs → CNF 4011 variables (3807 auxiliary), 6057 clauses · built in 3.09ms
[redsat] cost by source line (shared circuitry counts at the first line needing it)
[redsat] line unknowns times inputs AND gates clauses share source
[redsat] 8 6 24 30 24 0% [5, 3, ?, ?, 7, ?, ?, ?, ?],
[redsat] …
[redsat] 16 6 24 30 24 0% [?, ?, ?, ?, 8, ?, ?, 7, 9],
[redsat] 20 ×9 0 2,146 1,984 33% require all_different(grid[i]) // row i
[redsat] 21 ×9 0 2,210 2,101 35% require all_different([grid[r][i] for r in 0..9]) // column…
[redsat] 24 ×9 0 1,840 1,768 29% require all_different([grid[top + r][left + c] for r in 0..…
[redsat] search with portfolio of CaDiCaL ×4…
[redsat] searched 2 SAT calls · 1 solution · 21.26ms (CNF grew to 4011 variables, 6058 clauses)
[redsat] finished in 25.59ms: 94 statements executed, no calls inlined, 1 solve taking 24.54ms
| Line | Says |
|---|---|
loaded | which files make up the program (yours, the standard library <prelude>, and imports), and how long parsing and type checking took |
solve #N | a solve is starting, and where it is |
model | its mode (first, all, unique, with limit and minimize/maximize if given), how many requirements it sees, and how many terms the program’s constraints add up to |
unknowns | how many unknowns it involves, how many domain inference already pinned to a single value, and how long inference took; then up to eight of them with their ranges and widths (unnamed ? holes are shown by their line and column) |
space | the total number of bits the solver must decide, and so the number of candidate assignments. A brute-force search would try them all; the SAT solver typically explores a tiny fraction |
circuit | the size of the Boolean circuit and of the CNF formula built from it (the auxiliary variables stand for the circuit’s gates), and how long building them took |
cost | where that size comes from, line by line: see below |
search | which SAT solver is running |
searched | how many SAT calls and solutions there were, how long the search took, and how big the formula grew (enumeration and optimization add clauses as they go) |
deepening | no solution was found within the current bounds of unbounded integers, so RedSAT retries with twice as many bits |
domains | contradictory … no solution: domain inference alone proved there is no solution, without calling the solver |
finished | the totals for the run: statements executed (counting each loop iteration and inlined call again), function calls inlined and how deeply they nested, and the time spent in solves |
Program output appears between these lines as it is printed. See
Performance tips for how to act on what --verbose shows.
Where the cost comes from
Like a database’s EXPLAIN ANALYZE, the cost table breaks the problem down by source line,
so you can see which statements make it big. Here are the 100-digit factoring example’s
lines:
$ redsat examples/factor100.rsat --verbose
…
[redsat] circuit 291413 AND gates over 3758 inputs → CNF 280006 variables (279672 auxiliary), 824713 clauses · built in 357.16ms
[redsat] cost by source line (shared circuitry counts at the first line needing it)
[redsat] line unknowns times inputs AND gates clauses share source
[redsat] 16 2 334 657 972 0% var x, y
[redsat] 19 0 221,601 662,644 80% require x * y == n
[redsat] 22 0 0 2 0% require is_odd(x) and is_odd(y)
[redsat] 26 0 0 0 free require x > 1 and x <= root and y > root
[redsat] 29 0 0 0 free require x <= y
[redsat] 36 ×10 3,424 61,766 161,095 20% require x % m * (y % m) % m == n % m
[redsat] 42 0 0 0 free require x >= 10 ^ 49
[redsat] free: folded into the inferred ranges (it may narrow the unknowns), so it needs no circuit
| Column | Says |
|---|---|
unknowns | how many unknowns the line declares (each ? hole is one) |
times | how many requirements the line made, when more than one (a require in a loop makes one per iteration) |
inputs | the bits the solver must decide that the line introduced: an unknown’s bits, or auxiliary ones, such as the quotient behind each x % m |
AND gates | the circuit the line added |
clauses | the CNF clauses the line added, and their share of the total |
Some rules for reading it:
- Circuitry that several lines share counts once, at the first line that needs it, in program order. A later line that only reuses it shows little or nothing.
- A requirement marked free costs nothing because domain inference absorbed it. That does
not make it useless: it may have narrowed the unknowns, and so shrunk every other line. Above,
x >= 10 ^ 49is free, yet it is the reasonyneeds 168 bits instead of 326. - What happens inside a standard-library function is charged to the line that calls it. What happens inside your own functions is charged to their lines.
- Long programs list their 24 costliest lines, and sum up the rest in one row.
The built-in solver
--solver builtin uses RedSAT’s own SAT solver instead of CaDiCaL. It is a conflict-driven
clause-learning (CDCL) solver written in pure Rust, with the same interface, so every feature
works with it. It is much slower on hard problems, but needs no native code, so it runs
anywhere Rust does, including in a web browser.
Configuration: redsat.toml
Like tsconfig.json for TypeScript, an optional redsat.toml file configures the compiler for
every program in its directory and below. RedSAT looks for it in the program’s directory, then
in each parent directory, and uses the first one it finds. --config <file> names one
explicitly instead.
[compiler]
strict = true # turn on every strict check below
explicit-types = "unknowns" # "off" | "unknowns" | "all" (default "off"; strict: "unknowns")
unbounded-ints = "error" # "deepen" | "error" (default "deepen"; strict: "error")
fallback-int-bits = 32 # first magnitude tried for unbounded integers
max-int-bits = 256 # stop deepening beyond this
Every key is optional, and an empty file is fine. Unknown keys are errors, so a typo cannot go unnoticed.
Options
| Key | Values | Default | Command line |
|---|---|---|---|
strict | true, false | false | --strict |
explicit-types | "off", "unknowns", "all" | "off" | --explicit-types |
unbounded-ints | "deepen", "error" | "deepen" | --unbounded-ints |
fallback-int-bits | 1 to max-int-bits | 32 | --fallback-int-bits |
max-int-bits | up to 65536 | 256 | --max-int-bits |
explicit-types
Which variable declarations need a type annotation.
"off": types may always be inferred."unknowns": every unknown (avarwithout an initial value) needs a type, like TypeScript’snoImplicitAny."all": everyvarneeds a type, evenvar n: int = 42.
These checks apply to your code (and the files it imports), not to the standard library’s own functions.
var x, y
var n = 42
require x + y == n
error: `x` needs a type annotation
--> main.rsat:1:5
|
1 | var x, y
| ^ no type given
= note: required by the compiler option explicit-types = "unknowns"
= help: annotate it, e.g. `var x: int`
error: `y` needs a type annotation
--> main.rsat:1:8
|
1 | var x, y
| ^ no type given
= note: required by the compiler option explicit-types = "unknowns"
= help: annotate it, e.g. `var x: int`
unbounded-ints
What to do with an integer unknown whose range cannot be inferred.
"deepen": warn, and search with growing bounds:|x| < 2^fallback-int-bitsfirst, doubling the number of bits after each “no solution”, up to2^max-int-bits. Solutions found are genuine; “no solution” only covers the bounds searched. See Unbounded integers."error": reject the program, asking for bounds.
fallback-int-bits and max-int-bits
The first and the largest magnitude, in bits, tried for unbounded integers with
unbounded-ints = "deepen".
Strict mode
strict = true (or --strict) turns on the whole family of strict checks at once:
explicit-types = "unknowns" and unbounded-ints = "error". A strictly checked program declares
the type of every unknown and gives every integer a finite range, inferred or declared:
var x: int[0..=100]
var y: int[0..=100]
require x + y == 42 and x == 2 * y
solve x, y
x = 28, y = 14
var x: int
require x > 5
solve x
error: cannot infer a finite domain for `x`
--> main.rsat:1:5
|
1 | var x: int
| ^ unbounded
= note: required by the compiler option unbounded-ints = "error"
= help: give it bounds, e.g. `var x: int[0..=1000]`, or a constraint that limits it
Precedence
Settings are combined from four layers, each overriding the ones before:
- the built-in defaults;
- what
strictimplies; - keys set explicitly in
redsat.toml; - command-line flags.
So a strict project can still opt out of a single check, by setting its key explicitly:
[compiler]
strict = true
unbounded-ints = "deepen" # strict, except for this one check
Diagnostics
RedSAT reports problems as diagnostics, which point into your source code. When running a program, they are printed to standard error after the program’s output.
Anatomy of a diagnostic
var flag: bool
var n = 3
require flag + n > 2
error: expected `int`, found `bool`
--> main.rsat:3:9
|
3 | require flag + n > 2
| ^^^^ this is `bool`
- The first line gives the severity and the message.
-->gives the file, line and column.- The source line follows, with
^^^^under the code in question and, sometimes, a label. - Further locations, introduced by
:::, show related places: the other requirements of a contradiction, the call that led to an error inside a function, or theimportthat brought in a file. - Lines starting with
= note:add context, and= help:suggests a fix.
There are three severities:
| Severity | Means |
|---|---|
error | The program is wrong and stops. redsat exits with status 1. |
warning | Something is probably not what you meant, but the program runs to the end. |
note | Information, such as the explanation of a “no solution”. |
When errors are found
- Syntax and type errors are found before anything runs, by
redsat check, by the editor and by every run. All of them are reported at once. - Elaboration errors are found while the known part of the program runs: an index out of range, a value that must be known but depends on unknowns, runaway recursion. The program stops at the first one, after printing whatever it printed before. The editor’s language server finds these too, because it elaborates the program the same way.
Common messages
Syntax
| Message | What to do |
|---|---|
unknown operator `&&` (or ||, !) | Use and, or, not (or !=). |
comparisons cannot be chained | Write a < b and b < c. |
expected the end of the statement (a line break or ;) | One statement per line, or separate them with ;. |
expected = with a bare expression does nothing on its own | Write require … or print … in front of the expression. |
only a single variable can have an initial value | Declare the variables on separate lines. |
unterminated string | Strings must close on the same line. |
unclosed `{` in string | Close the interpolation, or write \{ for a literal brace. |
Names and types
| Message | What to do |
|---|---|
unknown variable `x` | Declare it first. Inside a function, pass it as a parameter. |
expected `int`, found `bool` | The operands of an operator, or the arguments of a call, have the wrong types. |
cannot infer the type of `x` | Annotate it: var x: int. |
cannot infer the type of this `?` | Use ? where the type is known, e.g. var x: int = ?. |
an unknown array needs a length | Give the length: [int; 5]. |
`x` is already declared in this scope | Assign with = instead of declaring again, or pick another name. |
`sum` is a built-in name | Give your function, enum or struct another name. |
`f` might end without returning a value | Make every path end with return. |
`f` takes 2 arguments, but 3 were given | Check the call against the declaration. |
`Point` has no field `z` | The help line lists the fields. |
named arguments are only for struct constructors | Pass function arguments by position. |
`x` needs a type annotation | Required by the explicit-types option: annotate it. |
Known versus unknown
| Message | What to do |
|---|---|
this value depends on unknowns, so it cannot be shown here | Print it inside a solve body. |
cannot print under a condition that depends on unknowns | Print inside a solve body. |
a range bound must be known at compile time (also: a loop bound, an array length, limit, the exponent, the shift amount, a bit width) | Use a known value here; see Knowns and unknowns. |
this loop's condition depends on unknowns | Add a bound: while … bound K { … }. |
an array comprehension cannot filter on unknowns: its length would depend on them | Use sum, count, all or any, or move the condition into the element. |
calls nested more than 200 deep | Recursion must stop on known values. Use a loop instead. |
`solve` must be a top-level statement | Move the solve out of the function or symbolic if. |
`require` is not allowed inside a `solve` body | Move it before the solve. |
Values
| Message | What to do |
|---|---|
index 3 is out of range for length 3 | Indices count from 0. |
10 is outside the declared range [0, 9] | Check the range: int[0..10] excludes 10. |
the range `5..5` contains no values | lo..hi excludes hi; use lo..=hi to include it. |
division by zero | A known value was divided by 0. |
strings cannot be changed in place | Build a new string with +. |
the loop did not finish within 10000000 iterations | A known while loop never ends; check its condition. |
Solving
| Message | Means |
|---|---|
`solve unique` found more than one solution | The notes show two different solutions. |
`limit` cannot be combined with `unique` | unique always looks for exactly two. |
cannot infer a finite domain for `x` | Required by unbounded-ints = "error": give x bounds. |
warning: could not infer bounds for …; searched |value| < 2^32 | The search was not complete: give the unknowns bounds. |
warning: `s` has no length bounds; lengths up to 32 are considered | Declare the lengths: string[1..=10]. |
warning: this requirement is always false, so the problem has no solution | A requirement on known values is false. |
note: no solution: these requirements cannot all hold together | See When there is no solution. |
note: no solution: this requirement can never hold | That requirement is impossible on its own. |
Imports
| Message | What to do |
|---|---|
cannot find `file.rsat`: … | Paths are relative to the importing file. |
an imported file may only declare functions, enums and structs | Move the other statements into the program. |
`square` is declared twice | Two files declare the same name. |
Internal errors
Before reporting an answer, RedSAT checks it against every requirement, using the language’s own
rules for known values. If an answer ever fails that check, RedSAT reports
internal error: the solver's answer violates this constraint instead of printing a wrong
answer. That would be a bug in RedSAT: please report it, with the program.
How RedSAT works
You never need to know any of this to use RedSAT, but it helps to understand why some models
are fast and others slow. The full design, with the reasoning behind each decision, is in
docs/design.md in the repository.
The pipeline
program.rsat
│ lexer, parser
▼
syntax tree ── names, type inference, strict-mode checks
│ elaboration: run known code, unroll loops, inline calls
▼
word-level constraints over integers and booleans
│ at each solve: domain inference, exact sizing
▼ bit-blasting
Boolean circuit (an And-Inverter Graph)
│ Tseitin encoding
▼
CNF formula ──▶ SAT solver (CaDiCaL, or the built-in solver)
│
▼
model ──▶ decode into program values ──▶ self-check ──▶ solve body
Every step takes polynomial time in the size of the program, the number of loop iterations and inlined calls, and the bit widths involved. The hard part, the actual search, is left to the SAT solver.
1. Parsing and type checking
The program, the files it imports and the standard library are parsed into one syntax tree. The
type checker infers the type of every variable and expression, and applies the
strict-mode checks. redsat check stops here.
2. Elaboration: running the known part
Next, RedSAT runs the program, with a twist: values may be unknown.
- Known values are computed right away, with arbitrary-precision integers.
- Loops over known ranges are unrolled, and function calls inlined.
- Each assignment creates a new version of a variable, so mutation needs no special handling.
- An
ifon an unknown condition runs both branches, and merges the variables they assign. - Operations on unknowns are not computed but recorded, as terms like
x * y == 4295229443, and eachrequireon unknowns adds a constraint.
When a solve is reached, the recorded constraints are handed to the next stages.
3. Domain inference and exact sizing
To build a circuit, RedSAT needs to know how many bits every integer has. It works that out in two steps:
Narrowing the unknowns. Every integer unknown starts with its declared range, or with “any integer”. RedSAT then propagates bounds through the requirements that always apply (those not under an unknown condition), until nothing changes or an iteration cap is reached (the cap keeps compile time polynomial). For example:
x > 1givesx ≥ 2;x * y == nwithx, y ≥ 2givesx ≤ n / 2;a*a + b*b == totalwithtotal ≤ 50gives|a| ≤ 7;x <= ytogether withx * y == ngivesx * x ≤ n, sox ≤ √n.
Sizing everything else. From the unknowns’ ranges, interval arithmetic gives every
intermediate result a range it is guaranteed to lie in, and so its exact number of bits, in
two’s complement when it can be negative. With x and y below 2^27, x * y gets 54 bits.
Overflow is impossible by construction.
--stats, --verbose and the editor’s hovers show the inferred ranges.
4. Bit-blasting: building the circuit
Each word-level operation becomes a small circuit over the bits of its operands, built from 2-input AND gates and inverters (an And-Inverter Graph):
| Operation | Circuit | Size |
|---|---|---|
a + b, a - b | ripple-carry adder, carry kept | O(n) |
a * b | shift-and-add multiplier, full product | O(n·m) |
==, <, <= | comparators | O(n) |
if c {a} else {b} | a multiplexer per bit | O(n) |
a / b, a % b | a fresh quotient and remainder with q·b + r == a, 0 ≤ r < abs(b); powers of two are bit slices | O(n·m) |
xs[i], i unknown | a chain of multiplexers over the elements | O(len·n) |
all_different | an inequality per pair of elements | O(len²·n) |
sum, count | a balanced tree of adders | O(len·n) |
The graph is hash-consed: the same gate is never built twice. It is also simplified as it is
built (a ∧ 0 = 0, a ∧ a = a, …), so constants propagate for free: a multiplier with one
known operand shrinks to a few adders.
5. CNF encoding
SAT solvers read formulas in conjunctive normal form (CNF): a list of clauses, each an “or” of literals. RedSAT translates the circuit with the Tseitin encoding, which gives every gate a fresh variable and keeps the formula linear in the size of the circuit. On top of that:
- a gate that is only ever required to be true (or false) only gets the clauses for that direction (the Plaisted–Greenbaum refinement), roughly halving the clause count;
- required “and“s are split into separate clauses, and required “or“s become single clauses.
6. Solving
The CNF formula goes to the SAT solver, a conflict-driven clause learning (CDCL) solver. It assigns variables, propagates their consequences, and when it hits a contradiction, learns a new clause that rules out the cause. Modern solvers handle formulas with millions of clauses.
RedSAT uses CaDiCaL by default. Its own pure-Rust CDCL
solver (--solver builtin) behaves the same, more slowly. Both are incremental: clauses can be
added between calls, and a call can make temporary assumptions. RedSAT relies on that for:
solve all: after each answer, a blocking clause says “differ from this answer in at least one of the listed variables”, and the solver is called again. Blocking only the listed variables is what makes projection work.solve unique: one call for the answer, one more to show there is no other.minimize/maximize: for counts, a core-guided search that raises a lower bound until a solution meets it; otherwise a binary search, each probe a temporary assumption (“objective ≤ m?”). See Optimization.- Explanations: each source line’s requirements get a selector literal, and the solver reports which selectors its proof of “no solution” used. See When there is no solution.
7. Decoding and the self-check
The solver’s answer is a true/false value for each variable. RedSAT reads the bits of the
unknowns, turns them back into integers, booleans, characters, strings, arrays and structs, and
then checks the answer against every requirement, using the language’s own rules for known
values. Only then is the answer shown, or handed to the solve body. An answer that failed the
check would be reported as an internal error, never printed as if it were right.
Performance tips
RedSAT turns your program into a SAT problem in polynomial time, but solving that problem can take exponential time: the problems RedSAT is good for are typically NP-hard. In practice, SAT solvers are remarkably fast on most real problems, and a few modelling habits make a big difference.
Measure first
Run with --verbose (or --stats) and look at three numbers for the slow solve:
[redsat] space 54 decision bits → 2^54 candidate assignments
[redsat] circuit 5948 AND gates over 54 inputs → CNF 5832 variables (5778 auxiliary), 16880 clauses · built in 20.79ms
[redsat] searched 1 SAT call · 1 solution · 102.73ms (CNF grew to 5832 variables, 16880 clauses)
- Build time versus search time. If built in is large, the problem is big: look at loops and calls that generate many requirements. If searched is large, the problem is hard for the solver: read on.
- Decision bits (
space) are the bits the solver has to choose. Fewer is better, and each bit you save halves the space a naive search would face. - Circuit size. Hundreds of thousands of gates are fine. Tens of millions are not.
- SAT calls.
solve allmakes one call per answer,uniquetwo, and an optimization one per bit of the objective’s range, roughly.
Give unknowns tight ranges
The single most effective habit. Every unknown’s range decides its number of bits, and with them
the size of every circuit it flows into. int[1..=9] needs 4 bits; a plain int that RedSAT
cannot bound starts at 33 and grows from there.
- Declare the range when you know it: a digit is
int[0..=9], an index isint[0..N]. - Let requirements bound the rest:
x > 1andx * y == nalready boundxandy. - Check the inferred ranges with
--statsor by hovering in the editor. An unknown with a much wider range than you expected is a hint.
Prefer addition to multiplication
A sum of two n-bit numbers costs about n gates; a product of two unknowns costs about n²,
and multiplier circuits are notoriously hard for SAT solvers. Factoring a 64-bit number is easy
to state and very hard to solve.
- Multiplying by a known number is cheap:
25 * quartersis just a few adders. - A product of an unknown and a 0/1 decision is better written as a condition:
sum(w[i] for i in 0..n if take[i])rather thansum(w[i] * x[i] …). - Exponents and products of unknowns (
x * x * x) multiply circuits too.
Break symmetries
If the answers of your problem come in groups of “the same answer in disguise” (interchangeable colours, machines, teams, items), the solver may explore each disguise separately. One or two symmetry-breaking requirements can cut the work by orders of magnitude, especially when proving that there is no solution or that an answer is optimal.
Choose good unknowns
The way you represent an answer matters more than any trick. In N-Queens, one column number per row makes “one queen per row” automatic, while a yes/no per square needs it as a constraint. Use the modelling questions as a checklist.
Mind what you ask for
solve(the first answer) is the cheapest.solve uniqueproves something extra, which can cost more than finding the answer.solve allon a problem with millions of answers will take a while; count a sample withlimit, or step through them with--interactive.- Optimization repeats the search many times. Tighter bounds on the objective mean fewer probes.
- Keep
while … bound Kbounds as small as your problem allows: every iteration is a copy of the loop body in the circuit.
Expect heavy tails
Solving times are sensitive to small changes. Two encodings of the same problem, or the same encoding with the factors in a different order, can differ by orders of magnitude on one instance and swap places on the next. When comparing models, try several instances before drawing conclusions.
FAQ
Why SAT?
Because SAT solvers are some of the most heavily optimised search engines in existence. Decades of research and yearly competitions have made conflict-driven clause learning solvers astonishingly good at the problems people actually meet, from hardware verification to scheduling. SAT is also a universal target: every problem in NP can be reduced to it in polynomial time.
RedSAT’s job is to do that reduction for you, from a program that reads like ordinary code, and to do it well: exact arithmetic, tight bit widths, compact encodings. The solver does the searching.
Is every program fast, then?
No. The problems RedSAT is good for are mostly NP-hard, and no known algorithm solves every instance quickly. The reduction to SAT always takes polynomial time, but the solver may need exponential time on hard instances. Factoring products of two large primes is an example that is easy to write and very hard to solve.
In practice, many real problems solve in milliseconds, and the Performance tips help with the rest.
Can integers overflow?
Never. Integers are mathematical integers, and every intermediate result gets as many bits as
its value can need. A type like uint<8> limits what a variable may hold, not the arithmetic:
a + b may be 510 even if a and b are uint<8>. If you want arithmetic that wraps around
like a CPU’s, write it: (a + b) % 256.
What if RedSAT cannot bound an integer?
Then it warns you, and searches with growing bounds: first 32-bit magnitudes, then 64, and so on
up to 256. Any answer it finds is genuine, but “no solution” then only means “none within the
bounds searched”. Give the unknown a range to make the search complete, or turn the warning into
an error with unbounded-ints = "error". See Unbounded integers.
Does RedSAT have macros?
No, and none are planned, because functions already do that job. Every function call is
inlined at compile time: the function’s body is run right where it is called, with the
arguments in place of the parameters. On known arguments that is compile-time computation, much
like a macro or C++’s constexpr, and loops in functions unroll into as many requirements as
you need. Functions are also hygienic: they only see their own parameters and variables, so
they cannot capture or clash with the caller’s names.
And unlike macros, the same function works on unknowns too, where its body becomes part of the circuit. See Functions.
Is the answer always right?
Every answer is checked against all requirements, using the language’s own rules for known values, before it is shown. If the solver ever produced a wrong answer (or RedSAT built a wrong circuit), you would get an internal error instead of a wrong answer.
“No solution” is a proof, as long as every unknown had a finite range. With unbounded integers it only covers the bounds that were searched, and RedSAT says so.
Can I use floating-point numbers?
Not yet. RedSAT has exact integers, booleans, characters, strings, arrays, enums and structs. Fixed-point arithmetic is easy to write with integers (count in cents, or in thousandths).
How is RedSAT different from MiniZinc, Z3 or Prolog?
They are close relatives. MiniZinc is a modelling language for constraint solvers; Z3 is an SMT
solver with a rich API; Prolog searches by backtracking. RedSAT’s angle is to look and feel like
an ordinary imperative language, with var, if, loops, functions, mutation and early
returns that all work on unknowns, and to compile everything down to plain SAT, with exact
integers whose sizes are inferred.
Which SAT solver does RedSAT use?
CaDiCaL by default, and its own CDCL solver, written in
Rust, with --solver builtin. redsat dimacs runs either solver on a raw CNF file.
Where do I report a bug or suggest a feature?
In the RedSAT repository. Please include the program and the output, ideally cut down to the smallest program that still shows the problem.
Keeping the docs up to date
This guide is tested, so that it cannot silently drift away from the compiler. This page is for people changing RedSAT or the guide.
Building the book
The guide is an mdBook. From the repository root:
$ cargo install mdbook # once
$ mdbook build docs/guide # writes docs/guide/book/ (git-ignored)
$ mdbook serve docs/guide # serves it on http://localhost:3000, rebuilding on change
The book is meant to be published under /guide/, next to the online playground at the site
root.
Tested code blocks
crates/redsat-lang/tests/docs.rs reads every page under docs/guide/src/ and checks its RedSAT
code blocks against the compiler, using CaDiCaL like redsat does:
```rsat a complete program; it must run without errors
```rsat,check it must type-check (for programs too slow to run in the tests)
```rsat,error it must fail
```rsat,ignore not checked: a fragment that cannot stand alone (keep these rare)
A ```text block right after an rsat or rsat,error block, with only blank lines in
between, is the program’s expected output: what it prints, followed by its diagnostics. The test
compares them line by line, ignoring trailing whitespace. Programs are named main.rsat in
diagnostics. To show output that is not checked (a shell session, say), use a ```console
block, or put a sentence between the program and its output.
More attributes can follow the language, separated by commas:
file=NAMEalso saves the block asNAMEnext to the page’s other programs, so that other blocks on the same page canimport "NAME"it (see the Imports chapter);- compiler options, spelled like the command-line flags:
strict,explicit-types=…,unbounded-ints=…,fallback-int-bits=…,max-int-bits=….
Run the tests with:
$ cargo test -p redsat-lang --test docs
A failure names the page and line of the block. When a change in behaviour is intended (a better error message, a different but equally valid first solution), regenerate the expected outputs, then review the diff before committing:
$ REDSAT_BLESS=1 cargo test -p redsat-lang --test docs
$ git diff docs/guide
Outputs that list several solutions depend on the order in which the solver finds them, so changes to encodings can reorder them. That is expected; blessing updates them. Make sure the prose around a block does not depend on that order.
When the language changes
Two more tests keep the guide complete:
the_reference_documents_every_word_of_the_language(indocs.rs) fails when a keyword, type, built-in function or standard library function fromredsat_lang::syntaxis not mentioned, in code, in the reference chapters (docs/guide/src/reference/).the_guide_highlighter_knows_exactly_the_words_of_the_language(incrates/redsat-lang/tests/grammar.rs) fails when the guide’s syntax highlighter,docs/guide/assets/rsat-highlight.js, does not list exactly the words ofredsat_lang::syntax. mdBook highlights code with highlight.js, which does not know RedSAT; that script teaches it.
every_page_is_in_the_summary also checks that every page is listed in src/SUMMARY.md, since
mdBook leaves unlisted pages out.
So, when you add to the language:
- A keyword, type or built-in function: add it to the word lists in
rsat-highlight.js, document it in the right reference chapter, and, if it is something users will reach for, show it in the tutorial (“Learn RedSAT”). - A standard library function: add it to the table in
reference/standard-library.md, with its signature and a known-value example. - A new error message or a changed one: run the docs test; bless and review. Consider adding
it to
reference/diagnostics.md. - A command-line flag or a
redsat.tomlkey: updatereference/cli.mdorreference/configuration.md. - A new example in
examples/: consider a cookbook recipe, starting with the problem in plain words.
The design document, docs/design.md, remains the place for rationale and decisions; the guide
links to it rather than repeating it.