Write the rules.
Explore every outcome.

Photonic is a language of rules. A program is data and the rules that change it. The runtime explores every configuration those rules can reach, and Prism checks results exactly.

Light,
[Light] Red,
[Light] Green,
[Light] Blue
Three rules can consume Light. Each is a possible event, so the runtime explores three futures. Select a configuration to see the events that leave it.

Each program in this book ran in the Rust runtime compiled to WebAssembly, and each graph is its real output. While the engine is live, you can edit any example and run it again.

To run Photonic on your own machine, download photonic for macOS, Linux or Windows from the releases page, or run bazel run //:install in a checkout. Save the program above as light.wave, then list where its runs end and check that one reaches Red:

photonic explore light.wave
photonic check light.wave --reach Red

Chapter 11 covers the command line, the Bazel rules and the questions Spectrum answers.

Part one

The language

Language · 1

Atoms, particles and coherences

Photonic has one kind of data: occurrences of atoms, grouped into particles, living in coherences.

An atom is any run of characters other than ( ) [ ] . , and whitespace, which is Unicode's pattern whitespace and the byte order mark. True, 0, ->, $x and 人 are atoms. An atom cannot hold another kind of space, such as the no-break space, a control character, or an invisible character that hides or reorders text, such as U+200B or U+202E; the joiners that emoji and some scripts need are part of it. Atoms compare by code point, without normalization, so é typed as one character and as e with a combining accent are two atoms. Atoms mean nothing by themselves; rules give them meaning.

A dot joins occurrences into a particle. A particle is unordered and counts repeats: A.B and B.A are the same particle, and A.A holds two occurrences of A.

A comma separates coherences, the independent places where particles live. A.B, C is two coherences. Particles side by side join as if a dot stood between them: A B is A.B. () is one empty coherence; an empty program has none.

A configuration is everything that exists at one moment: its coherences and the rules that are live.

Next: Rules consume and produce

Language · 2

Rules consume and produce

A rule names in brackets what it consumes, and beside them what it produces.

A.X,
[A] B
[A] B matched the A inside A.X, consumed it and produced B. It never mentioned X, so X stayed. X is the remainder.

A program lists its coherences and rules, separated by commas, in any order. Everything listed is part of the starting configuration, and a rule listed on its own is live there.

Matching is open: a pattern needs only its own occurrences, and the rest of the coherence passes to the output.

To consume the whole particle, name all of it:

A.X,
[A.X] B

An event consumes one match. Two occurrences of A take two events:

A.A,
[A] B

Several inputs, several outputs

Commas inside the brackets select several coherences, and a group after them produces several: [A, B] (C, D) consumes two coherences and produces two. Every output receives the remainder of every consumed coherence.

A.X, B.Y,
[A, B] (C, D),
[C, D] E
The first rule joins A.X and B.Y and splits into C and D; both carry X.Y. The second rule joins them again. The dashed arrow is an inference; chapter 6 explains it.

Empty inputs and outputs

RuleConsumesProduces
[A] Ban AB with the remainder
[A]an Anothing: the coherence is gone
[A] ()an Aone coherence holding only the remainder
[] Anothinga new coherence A, every time it fires
[()] Aany one coherencethat coherence with A added
[(), ()] Aany two coherencesone coherence: both remainders and A
A.X, B.Y,
[A],
[B] ()
[A] removes A.X entirely; [B] () leaves Y. The comma after [A] keeps the two rules apart. Without it they would be one term, as the next section shows.

Several brackets

Everything between two commas is one term, and its parts join, in any order. The brackets in a term are what it consumes, joined like any parts, and the rest of the term is what it produces. So C [A] is [A] C, and [A] [B] C is [A.B] C.

A.B.X,
[A] [B] C
One rule: its brackets join into [A.B], so it consumes A.B and produces C beside the remainder X.

Joining distributes inside brackets too: [A, B] [C] consumes A.C and B.C, two coherences.

The lens shows how each form reads. Compare [A] (B, C) with [A] B.C and [A] B, C, and [A], [B] C with [A] [B] C, C [A] [B] and [A] B C:

Next: Occurrences have identity

Language · 3

Occurrences have identity

Two occurrences can carry the same atom and still be different occurrences. Photonic tracks which is which.

When one event produces several outputs, they all receive the same remainder: the same occurrence appears in each. When those coherences join again, a shared occurrence counts once.

Seed.X,
[Seed] A.((), ()),
[A, A] ()
A.((), ()) is shorthand for two outputs, each A. They share one X, so joining them gives back one X.

Occurrences written separately are independent, and they add up:

A.(X, X),
[A, A] ()
Two coherences, A.X and A.X, with two independent Xs. Joining keeps both: X.X.

Adding up is arithmetic. A natural number can be a coherence of independent Units, and addition is a join:

Add.Unit.Unit,
Add.Unit.Unit.Unit,
[Add, Add] ()
2 + 3 = 5. The rule consumes both Add labels and joins the remainders, and the five independent units survive.

Every explicit output is a new occurrence. Two branches that each produce Y produce two Ys, even from one ancestor.

Identities are anonymous. Configurations that differ only in how occurrences are named are the same configuration, and the runtime stores it once.

Next: Every future

Language · 4

Every future

When several events are possible, the runtime explores all of them. The result is a graph: configurations are nodes, events are arrows.

An event is one rule applied to one match. Different rules, and different matches of one rule, give different events.

A,
[A] B,
[A] C,
[B, C] D
B and C are alternatives: each future holds one of them, never both, so [B, C] D never applies. Prism proves D unreachable.
A,
[A] (B, C),
[B, C] D
Here one rule with two outputs, [A] (B, C), produces B and C in the same configuration, so they can join. The program above lists two rules instead: [A] B, [A] C.

Only occurrences that coexist in one configuration can be matched together.

Cycles and endless programs

A,
[A] B,
[B] A
Returning to a configuration closes a cycle. The graph stays finite.
[] A
[] A adds a coherence every time it fires, so the graph never ends. Exploration stops at its budget and says so.

Exploration runs within budgets on configurations, coherences, occurrences, scopes, records and work. A search stopped by a budget can resume with a larger one. Until it finishes, whatever it has not found is unknown.

Next: Scopes

Language · 5

Scopes

A group that lists rules is a scope: a local place with its own rules, written like a program in parentheses. A rule's output opens one each time the rule fires.

Brew.Tea,
[Brew] (Kettle, [Kettle.Tea] Cup)
Consuming Brew opens a scope holding Kettle and the remainder Tea. The rule [Kettle.Tea] Cup fires, and because it is one of the scope's own rules, its output returns to the enclosing scope: Cup.

A scope works like a function body: it receives the remainder, runs its local rules and returns through them.

What a scope holds

A scope is a program in parentheses, so it holds any coherences, rules and scopes. Every coherence a rule introduces receives the remainder, inside a scope as outside:

Brew.Leaf,
[Brew] (Kettle, Cup, [Kettle, Cup] Tea)
Consuming Brew opens a scope with two coherences, and each receives the remainder: the same Leaf in both. The scope's rule joins them, the shared Leaf counts once, and Tea.Leaf returns.

Like any group that lists neither a coherence nor a scope, a scope such as ([A] B) holds the empty coherence (), so the remainder always has a place to go. A scope inside a scope returns to it, and sees the rules of every scope around it:

Brew.Leaf,
[Brew] ((Kettle, [Kettle] Hot), [Hot] Tea)
The inner scope's rule returns Hot.Leaf to the outer scope, and the outer scope's rule returns Tea.Leaf. The outer scope lists a scope, so it holds no coherence of its own.

A scope written in the program itself opens when the program starts: in Z, (X, [X] Y), the scope holding X returns Y beside Z.

Next: Inference

Language · 6

Inference

A rule can apply to what a configuration can become. The event happens at the original configuration.

A,
[A] B.C,
[B] D
In order, the rules give B.C and then C.D. But A can become B, so [B] D also applies to A directly: it consumes A and produces D. C existed only along the way, so it is not part of that result. The dashed arrow is the inferred event. No run of events one at a time ends at D: inference reaches configurations that such runs do not, and --plain explores only the runs.

Abstraction through rules

Inference makes abstraction ordinary. Here two ordinary rules make True and False count as Boolean:

Not.True,
[True] Boolean,
[False] Boolean,
[Not.Boolean] (
    [True] False,
    [False] True,
)
[Not.Boolean] needs a Boolean. True can become one, so the rule applies to Not.True. The scope receives the concrete True, not Boolean, and its local rule answers False.

Inference splits a match in two. Occurrences matched as written, here Not, are exact. Occurrences reached through evidence, here True seen as Boolean, are the witness. A literal output consumes both. A scope consumes the exact part and receives the witness. Hover an event to outline what it consumes: solid for exact, dashed for witness.

Every inferred event also has a deduction: the events that lead from its configuration to the one where its rule matched. Its row names that configuration, and hovering draws the path dotted. In the workbench, selecting a dashed hyperedge lists the deduction step by step.

And.True.False.Extra,
[True] Boolean,
[False] Boolean,
[And.Boolean.Boolean] (
    [True.True] True,
    [True.False] False,
    [False.False] False,
)
[True] Boolean and [False] Boolean lead to And.Boolean.Boolean.Extra, where [And.Boolean.Boolean] matches. The event happens at the start, where the operands are still True and False, so the scope receives True.False.Extra. One table row covers both operand orders, because True.False and False.True are one particle. Extra is remainder, so the answer is False.Extra.

A scope can use inference too. [False.Boolean] False says that False with any Boolean is False, so one row covers three rows of the table:

And.True.False.Extra,
[True] Boolean,
[False] Boolean,
[And.Boolean.Boolean] (
    [True.True] True,
    [False.Boolean] False,
)
Two deductions in a row. [And.Boolean.Boolean] matches And.Boolean.Boolean.Extra; inside the scope, [False.Boolean] False matches Boolean.False.Extra. A literal output consumes the witness too, so only Extra stays beside the answer. A row that named only False would leave the other operand behind as remainder.

Next: Rules are values

Language · 7

Rules are values

A rule in brackets inside a particle is a value. It can be produced, carried, matched, consumed and replaced.

Seed.A,
[Seed] ().([A] B)
[Seed] ().([A] B) produces the rule [A] B as a value, beside the remainder A. A rule value in a coherence is live and applies within that coherence, turning A into B. Inference also reaches Seed.B: executing a rule reads it without consuming it.
([A] B).A,
[[A] B] ().([A] C)
[[A] B] ().([A] C) matches the whole rule value [A] B, consumes it and produces [A] C. Matching compares complete code; a rule never looks inside another.

Loaded rules are live occurrences too, and a rule can consume one:

[A] B,
[[A] B] C
[[A] B] C consumes the loaded rule [A] B and produces C. The target lists every rule that survives.

Next: Fields and shorthand

Language · 8

Fields and shorthand

Particles are unordered, so a role needs its value attached. A one-rule value does that.

Digit.0.Carry.1 cannot say which number is the digit. ([Digit] 0).([Carry] 1) can: each role and its value form one rule value, a field.

Fields are live rules. Beside a bare P, the field ([P] True) fires and turns it into True. The theorems use this on purpose. The library keeps role names out of plain atoms, except the callback triggers Each and Operation and the operand sides Left and Right, which //library:test allows by name.

P.([P] True)

Shared prefixes

A dot distributes over a group: A.(B, C) means A.B, A.C, and (A, B).(C, D) means four coherences. A joined group builds nothing: Box.(A.B) is exactly Box.A.B, and a rule inside it is a field of the particle, never a scope. Side by side joins too, so A(B, C) is A.(B, C).

Next: Prism

Part two

Verification

Verification · 9

Prism

Prism answers one question: can this exact configuration be reached?

A target is written as a program and names the configuration that program starts in: every coherence, every occurrence, every live rule and every scope. A.X, [A] B reaches B.X, [A] B, where the rule is still live, but never plain B.X. A scope in a target is one the program opens at the start, since a scope a rule opens holds what the rule matched.

A.X,
[A] B
The start counts: every configuration reaches itself. While the engine is live, edit the targets and run again.
VerdictMeaning
reachedA supported configuration equals the target.
unreachableExploration finished without it. Only a complete exploration can say this.
unknownNeither: a budget stopped the search first. Unknown never passes a test.
[] A
Two coherences of A appear early. A.A never does, but the exploration never finishes, so Prism cannot prove it unreachable.

Direct paths

Large programs are checked along a direct path: one execution, followed until it reaches the target, returns to a configuration it has seen, or no rule applies. A path can prove a target reachable; it can never prove one unreachable. Programs that build linked data, and most theorems, are checked along paths.

Next: The workbench

Verification · 10

The workbench

Two views of one program. The state graph shows every configuration; the hypergraph shows how one execution moves through its coherences.

In the hypergraph each coherence is a lane that runs from the event that produced it to the event that consumes it. An event is a hyperedge: it consumes whole coherences and produces new ones, and every other lane passes it untouched. Lanes that never meet evolve independently. Select a configuration in the state graph to draw the execution that reaches it.

Every explored example in this book has a Workbench button that opens it here. For your own programs, the Lightbox gives the same views a full page, loads any file of the standard library with the files it needs, keeps your draft, and makes links that carry the whole program.

Filter by pattern

Type a pattern in the filter field, or press ⌘ K or / anywhere in the book. The workbench keeps what matches and everything computed after it, and hides the rest. The engine reads the pattern, the same way photonic select does, so filtering needs the live engine.

PatternMatches
BA coherence that holds B
B.XA coherence that holds both B and X
B, CA configuration in which two different coherences hold B and C
().([A] B)A coherence that holds the rule value [A] B
(K, [K] L)A scope that holds K and the rule [K] L
[B, C] DAn event that applies the rule [B, C] D
[A] C, [B] DAn event that applies either rule

A pattern is read as a program and matches the way a rule's input does: a coherence matches when it contains every occurrence the pattern names, and a scope when it holds every coherence, rule and scope the pattern names, whatever else it holds. Parts listed together match different parts, in any order. In the hypergraph, each coherence of a pattern selects lanes on its own.

Symmetry

The symmetry panel colors both graphs by the ways a program repeats itself under other names. A global symmetry renames the whole program into itself: in Parallel, exchanging A with B and C with D leaves every rule in place, so those atoms and the events of [A] C and [B] D share one color. A local symmetry is a group of rules that recurs under other names while the rest of the program tells the copies apart, like [True] Boolean and [False] Boolean in Conjunction. A block is a set of atoms that always appear together. Hover or select a symmetry to light what it relates, and clear the Color box for the plain graphs. Chapter 17 explains how they are found.

Next: Tests and tools

Verification · 11

Tests and tools

Bazel builds, runs and tests Photonic from source. It is the only tool a checkout needs; it downloads everything else.

load("//photonic:defs.bzl", "photonic_binary", "photonic_library", "photonic_test")

photonic_library(
    name = "logic",
    srcs = ["logic.particle"],
    deps = ["//library/boolean:not"],
)

photonic_binary(
    name = "example",
    srcs = ["request.wave", "value.particle"],
    deps = [":logic"],
)

photonic_test(
    name = "negation",
    source = "Invoke.Boolean.Not.True",
    target = ["False"],
    deps = ["//library/boolean:not"],
)

A library holds only rules. A binary combines the coherences of its sources and loads each library file once. .particle and .wave share one grammar; by convention .particle holds reusable definitions and .wave runnable programs.

These labels name packages of this repository, so the file builds inside a checkout. Another Bazel module adds bazel_dep(name = "photonic") with a git_override that names this repository and a commit, then writes the same labels from @photonic, as in @photonic//photonic:defs.bzl and @photonic//library/boolean:not. The library reference lists every target.

Test attributeMeaning
source, srcs, depsThe program: literal source, files and libraries.
targetComplete configurations, each with every loaded root rule added. "A, B" is one target with two coherences; ["A", "B"] is two targets.
expect"reached", the default, or "unreachable"; every target must meet it.
pathTrue follows a direct path per target, which can only expect reached.
everyTrue requires every schedule of plain events to end exactly at a target, and no run to go on forever; Laser explores the schedules without inference. It can only expect reached.
work, configuration, occurrence, scope, coherence, recordBudgets for work, configurations, occurrences, scopes, coherences and records.
size, tagsBazel's test size, small by default, and tags. A test that needs more than 2 GiB carries memory, which continuous verification skips.

Command line

bazel run -c opt //command:photonic -- lower program/language/inference.wave
bazel run -c opt //command:photonic -- run program/language/inference.wave
bazel run -c opt //command:photonic -- prism program/language/inference.wave --target target.wave

lower prints the program as JSON, run every configuration the program reaches by the handles the questions below use, and prism a verdict for the complete configuration in a target file, exiting 1 unless it is reached; --preserve adds every loaded root rule to the target, as photonic_test does. They explore with Laser, the default engine; --engine interpreter explores with the interpreter instead, which closes with the same answers. --library loads a rules-only file, --path follows a direct path, and --plain explores every schedule of plain events. Every command reads paths relative to where bazel run started.

bazel test -c opt //...
bazel run -c opt //program/language:inference
bazel test -c opt //program/language:conjunction.check

Asking questions

bazel run -c opt //command:photonic -- check program/language/conjunction.wave --reach False.Extra --exact --preserve
bazel run -c opt //command:photonic -- explore program/language/conjunction.wave
bazel run -c opt //command:photonic -- cause program/language/conjunction.wave s6
bazel run -c opt //command:photonic -- mcp

Spectrum answers questions about a program and every configuration it reaches. Answers name things by handle: r2 is a rule, s6 a configuration, e3 an event and s6.o0 an occurrence. The first command claims that the conjunction reaches exactly False.Extra with its rules, and the third shows the two events that get there.

CommandAnswer
checkDiagnostics, then a verdict for each claim: --reach, --avoid, --always, --inevitable, --outcome or --end. With --plain --engine metal, every schedule of plain events on the GPU.
exploreCounts, end configurations and how often each rule fires.
selectThe configurations or events that match a pattern.
inspectA rule, configuration, coherence, occurrence, scope or event.
causeWhy something is there: a path, a match and its deduction, or where an occurrence came from.
missWhy a target is not reached, or why a rule never fires.
stepThe events that can happen at a configuration.
compareThe configurations and events one program reaches and another does not.
shapePrograms grouped by shape, or one program's symmetries, as chapter 17 shows.

A claim holds, fails or is unknown. Unknown means a budget stopped the search or a direct path followed one run of many; it is never evidence of absence. --json prints each answer as data. mcp serves the same questions to agents over the Model Context Protocol, reading only files inside the directory it starts in, and the repository's .mcp.json starts it. Spectrum is the full contract.

This book

bazel run -c opt //book:serve
bazel run -c opt //book:record
bazel test -c opt //book:record.check

The server runs every example live in WebAssembly. //book:record reruns every example, lens and expression in this page and stores the results in book/record.js, which makes the book work as a local file. //book:record.check fails when that record is stale or an example contradicts its stated verdict.

Next: The standard library

Part three

The standard library

Library · 12

The standard library

The standard library is written in Photonic: 68 rule files in 14 packages. Rust only loads and checks it.

Every operation is named Type.Verb, and each type belongs to one package. A request carries Function; its answer carries Return. Scalar requests run inside Invoke, which is the whole of invoke.particle:

[Invoke] (
    Function,
    [Return] ()
)

Invoke opens a scope holding Function and the rest of the request. The scope's own rule [Return] () returns whatever accompanies Return. An implementation is a table:

[Function.Boolean.Not.True] Return.False,
[Function.Boolean.Not.False] Return.True,
[Boolean.Not.([Each] Boolean.Not)] Function.Boolean.Not
Invoke.Boolean.Not.True
Enter the scope, rewrite Function.Boolean.Not.True to Return.False, return False. The third rule lets collections name Boolean.Not as a callback. With inference, [Return] () can also apply at the start to the Return.False the table will write, and its literal output consumes that answer, so one future ends at (); every plain schedule ends at False.
Invoke.Ternary.Add.2.2
Digit tables answer with fields. In base three, 2 + 2 is digit 1, carry 1.

Conventions

PackageProvides
functionInvoke, Identity, Compose
booleanNot, And, Or, Equal
ternaryTrit Add, Sum, Multiply, Successor, Compare, Equal, Subtract, Select
binaryBit Sum and Multiply
carryKill, Propagate and Generate: Combine, Equal, Evaluate
collectionPairs: Produce, Copy, Repeat, Broadcast, Unpack, Choose, Map, Gather, Reduce
selectionFilter, Check, Count, Reduce
fieldPack and Unpack for positions 0 to 3 and values 0 to 2
streamA streaming Successor
chainLinked cells: Push, Read, Peek, Forget, Reverse, Erase
naturalUnbounded base-three naturals: copy, normalize, successor, add, subtract, difference, multiply, divide, compare
integerSigned Add, Subtract, Multiply, Divide
expressionTokens, parsing and evaluation of infix expressions
vectorRecursive vectors: link, insert, take, reverse, erase, stable merge sort

The library reference lists every request and answer.

Next: Linked data

Library · 13

Linked data

Unbounded values are linked: a handle coherence reaches cells elsewhere in the same scope.

A chain handle is Zero or a Head carrying a private seal and its methods. Requests sit beside the handle:

Request beside a chainAnswer
Push.symbolBuilt beside the longer chain
ReadYield.symbol beside the tail, or Yield.End.Zero
PeekSeen.symbol beside a new reference to the tail; the cells stay
ForgetClean once this reference is dropped

Every output of an event receives the remainder, so a rule with two outputs duplicates a handle. Programs therefore move a chain by sending it on and forgetting the other copy, then continue on Clean. This program pushes 2, 0 and 1, reverses the chain and reads back 2, 0, 1. It ends at Zero.Done: the last read leaves the empty chain Zero beside the answer.

Push.([Digit] 2).Zero, Stage.1,
[Built, Stage.1] (Push.([Digit] 0), Forget.Stage.2),
[Built, Clean.Stage.2] (Push.([Digit] 1), Forget.Stage.3),
[Built, Clean.Stage.3] (Function.Chain.Reverse, Forget.Inspect.Start),
[Return.Chain.Reverse, Clean.Inspect.Start] (Read, Forget.Inspect.0),
[Yield.([Digit] 2), Clean.Inspect.0] (Read, Forget.Inspect.1),
[Yield.([Digit] 0), Clean.Inspect.1] (Read, Forget.Inspect.2),
[Yield.([Digit] 1), Clean.Inspect.2] Done

A vector holds any value that answers Forget, including naturals, chains and other vectors, by reference. Function.Vector.Sort sorts a vector of naturals with a stable, adaptive merge sort: one pass splits the input into runs, balanced passes merge them pairwise, and alternating orientation means no merge result is ever reversed. For n items in r runs it makes at most n − 1 + n⌈log₂ r⌉ comparisons.

bazel test -c opt //program/ternary:reversal.check
bazel test -c opt //program/vector:sort.check

Next: Arithmetic

Library · 14

Arithmetic

A natural is a chain of base-three digits, least significant first. All of its arithmetic runs as Photonic rules.

Function.Natural.Add sits beside Operand.Left and Operand.Right and answers Return.Natural.Add. Subtraction answers a number or Error.Underflow; division answers a quotient and a remainder, or Error.Divisor; comparison answers Less, Equal or Greater and leaves both operands intact. Integers add a sign: zero is Positive, and division truncates toward zero.

The expression package parses and evaluates infix expressions with precedence, left association, parentheses and unary minus, and answers Error.Syntax, Error.Stack or Error.Divisor for bad input. Below, the host only turns your characters into a token tape. Parsing and every digit of arithmetic are Photonic rules.

The panel shows the program your expression becomes. While the engine is live, step through every event of its path.

Next: Proof by execution

Part four

Proof

Proof · 15

Proof by execution

A theorem program lists every case of a claim, checks each one, and concludes Theorem only when all of them hold. Prism checks that it reaches exactly Theorem.

Case.(([P] True), ([P] False)),

[Claim] Function.Boolean.Not.Once.P,
[Return.Once] Function.Boolean.Not.Twice,
[Return.Twice] Function.Boolean.Equal.Verdict.P,

[Holds.(([P] True), ([P] False))] Theorem
Negating twice returns the original value. Step through every event of the proof.

The first line expands into two cases. ([P] True) is a field, so every P in its case becomes True. case.particle gives each case its own scope: a true verdict returns Holds with the case's assignment, a false one Counterexample. The last rule needs one Holds for every assignment, and consuming them leaves exactly Theorem.

Four kinds of claims

ClaimHow it decides each case
EvaluatedRuns the library's own operations and compares the answers.
CoveredAssigns truth values to propositions about unknown relations; each rule closes the cases where a hypothesis fails or the conclusion holds.
JudgedDerives values from definitions, then a judge table upholds or overturns each case.
DerivedAn equational proof: facts are equations, rules are congruence, transitivity and earlier theorems.

Every term is Photonic structure that rules can match: Times.([Left] X).([Right] Y), Meet.([Of] X).([Of] Y), Less.([Left] X).([Right] Y), Equation.([Side] S).([Side] T). Two Of fields form a multiset, so commutativity needs no proof.

What is proved

1 · LogicThe laws of every Boolean algebra.
2 · RelationsLaws of every relation satisfying their hypotheses: orders, equivalences, partitions.
3 · Constructed typesOrders on products, sums and sequences, and the ternary comparison.
4 · Arithmetic schemesThe carry algebra and induction steps that hold at every width.
5 · CombinatoricsPigeonhole, Schur, van der Waerden and Ramsey numbers, each refuted one size below.
6 · AlgebraGroup, lattice and ring laws derived from their axioms.
7 · CountingThe ternary add, sum, subtract, multiply and compare tables are counting with the successor.
8 · Chain cellsA cell returns exactly its item and the chain below, for every item its rules do not name.
9 · Linked naturalsEach step of the library's own addition, subtraction, comparison, trim, reversal and successor engines.
10 · Plane geometryThe 48 propositions of the first book of Euclid's Elements, each from the postulates, the common notions and the propositions before it.

134 claims: 129 proofs and 5 refutations. Layers 7 to 9 prove the standard library itself, so linked addition, subtraction, comparison and successor are correct at every width. The theorem guide explains how to write one.

bazel test -c opt //theorem/...

Next: Euclid's first book

Proof · 16

Euclid's first book

The first book of Euclid's Elements proves 48 propositions, from the equilateral triangle to the theorem of Pythagoras and its converse, on five postulates and five common notions. Each proposition here is a Photonic program that reaches exactly Theorem, and later propositions cite earlier ones as single rules.

Choose a proposition and step through its proof. The figure grows as the proof names its points and lines; each step outlines what it uses and highlights what it gives. The panel beside the figure reads the same facts in the usual notation of geometry and names the postulate, common notion or earlier proposition behind each step. The arcs above join every proposition to the earlier ones it cites.

Magnitudes and facts

A magnitude is a field that names its points: ([Line] A.B) is the straight line AB, ([Angle.B] A.C) the angle ABC, ([Area] A.B.C) the triangle ABC and ([Square] A.B) the square on AB. A fact says that two magnitudes are equal, as Equal.([Line] A.C).([Line] A.B) does, and a sum is a field of its parts. There is no order on magnitudes, so a greater one is a whole with a part: Equal.([Line] A.C).([Sum] ([Line] A.B).Excess) says that AC is AB and something more.

C,
Equal.([Sum] ([Line] A.B).([Line] A.B)).([Sum] ([Line] A.B).([Line] A.B)),

[Equal.([Sum] ([Line] A.B).([Line] A.B)).([Sum] ([Line] A.B).([Line] A.B))] (Equal.([Sum] ([Line] A.B).([Line] A.B)).([Sum] ([Line] A.B).Excess), Equal.([Sum] ([Line] A.B).([Line] A.B)).([Sum] ([Line] A.B).Excess), Equal.([Sum] ([Line] A.B).([Line] A.B)).([Sum] ([Line] A.B).Excess)),
[C, Equal.([Sum] ([Line] A.B).([Line] A.B)).([Sum] ([Line] A.B).Excess), Equal.([Sum] ([Line] A.B).([Line] A.B)).([Sum] ([Line] A.B).Excess), Equal.([Sum] ([Line] A.B).([Line] A.B)).([Sum] ([Line] A.B).Excess)] (Equal.([Line] A.C).([Line] A.B), Equal.([Line] B.C).([Line] A.B)),

[Equal.([Line] A.C).([Line] A.B), Equal.([Line] B.C).([Line] A.B)] Theorem

Proposition 1 is three rules. The atom C is the point to construct, and only the rule that constructs it consumes it. The first rule is Common notion 5, the whole is greater than the part: AB and AB together exceed AB. The second is Postulate 3 with a fact Euclid reads from his figure: circles about A and B meet when each radius, and the distance AB, is less than the other two together, so the rule takes those three facts, consumes C and places it on both circles. The last rule turns AC = AB and BC = AB into Theorem.

Axioms and propositions are rules

Each postulate and common notion is a rule schema, written out wherever a proof uses it. Common notion 1 turns Equal.x.y and Equal.y.z into Equal.x.z, and Common notion 5 turns a magnitude equal to itself and something more into Absurd. Rules consume their premises, so a proof states a fact as often as it uses it, and reaching exactly Theorem shows that every fact was used.

A proposition, once proved, is a rule of the same kind. Proposition 5 applies proposition 4 in one event instead of repeating its proof, and 47 applies six earlier propositions the same way. The summary above the figure counts both: the events a proof takes, and the events it would take with every citation replaced by the proof it cites, down to the postulates. Proposition 48 takes 12 events; unfolded, it would take more than five million.

Every arrangement

A proof by contradiction opens a scope for its supposition. (Suppose.Short, [Absurd] Refuted.Short) closes as Refuted.Short only when its case reaches Absurd, and nothing inside the scope reaches the rest of the proof. Euclid often draws one arrangement of a figure and leaves the others to the reader. The programs list every one: proposition 4 refutes the four places other than F where the moved point could fall, proposition 7 both places where a second meeting point could lie, and proposition 35 proves its claim whether the parallelograms stand apart, overlap or touch. Stepping into a case redraws the figure in that arrangement.

Each proof also has an .order test, which runs every schedule of its events and passes only when each one ends at Theorem.

What Euclid assumes

Where Euclid reads a fact from his figure, the program states it: that two circles meet, where two lines cross, how a figure divides into triangles. The list of arrangements a case analysis covers comes from the figure too. The book's tests check every fact stated outside a refuted case against the coordinates of its drawing, and check that every citation is an instance of the proposition it cites. Euclid proves propositions 4 and 8 by moving one triangle onto another, and places a figure where he needs it in 44; superposition is one more rule, and the moved triangle keeps its sides, angles and area. He names parallelograms without defining them; here a parallelogram is a quadrilateral whose opposite sides are parallel. Proposition 48 relies on a lemma Euclid assumes, that squares on equal straight lines are equal and conversely, proved here from propositions 3, 4, 34 and 46.

bazel test -c opt //theorem/euclid/...

Next: Connections between fields

Proof · 17

Connections between fields

An atom is a name and nothing more. Programs that differ only in their names are one program, and Photonic finds them even when they come from different fields.

Rules compare atoms only for equality, so renaming the atoms of a program, one name for another, renames every configuration it reaches and every event between them. What a program means is the pattern its names form: its shape. photonic shape finds programs that share a shape, and the renaming between two of them is a dictionary from one vocabulary to the other. Hover a row of a dictionary to see its atom in every program.

Adding modulo 2, exclusive or and turning a card over are one structure: 0, False and Keep play one part, and 1, True and Flip the other. Multiplying the odd numbers modulo 8, toggling two switches and the symmetries of a rectangle share another shape. The quarter turns of a square also have four elements, but they are counting modulo 4, and no dictionary joins them to the switches: renaming leaves the switches' shape unchanged in 6 ways and the turns' in 2, and renaming a program never changes that number.

The renamings that leave a shape unchanged are its symmetries, and each gives another dictionary: any of Across, Along and Turn can stand for 3 modulo 8. Within one field, a dictionary shows a duality. Boolean.Or is Boolean.And with True and False exchanged, which is De Morgan's law. The lattice theorem that x ∨ y = y implies x ∧ y = x, with meet and join exchanged and x and y exchanged, is the theorem that x ∧ y = x implies x ∨ y = y.

How it works

Each program becomes a graph in which only the atoms are unnamed. Identical parts share one vertex, so only atoms can be interchangeable. Refinement splits the atoms by how they are used until no split remains, and a search tries each remaining choice. Whenever it finds a symmetry, it skips every choice that symmetry makes redundant, as the graph isomorphism programs nauty, bliss and Traces do. The least labeling it reaches names the atoms A, B, C and so on. That renamed program is the shape, and two programs are connected exactly when their shapes are equal. The dictionaries above come from the same search, run in this page.

A connection can also run inside one program. A group of rules may recur under other names although the program as a whole has no symmetry. Loaded with the libraries they need, the addition library moves its digits through the same ten rules that borrowing uses, with Add renamed Deduct, and the sorting library merges in both directions with the same 61 rules, Up and Down and Less and Greater among the names exchanged. photonic shape finds these local symmetries by growing groups one rule at a time from rules of equal shape and extending every copy the same way, as the frequent subgraph miners gSpan and GraMi grow patterns, and keeps the groups that account for the most of the program, as the compression heuristics of SUBDUE and Stitch do. The workbench and the Lightbox run the same analysis on every program and color the global symmetries, the local ones and the atoms that always travel together in both graphs.

bazel run -c opt //command:photonic -- shape library/boolean/and.particle library/boolean/or.particle
bazel run -c opt //command:photonic -- shape library/ternary/compare.particle
bazel build -c opt //library/vector:sort
bazel run -c opt //command:photonic -- shape "$(bazel info -c opt bazel-bin)/library/vector/sort.json"

Given several programs, shape groups them by shape and prints each renaming. Given one, it prints the program's shape and canonical form, its symmetries, the rules they exchange, and the groups of rules that repeat under other names. Bazel assembles each library with its dependencies into a .json program, which shape reads like source. --library loads rules, --target adds a configuration every renaming must keep, and --fix keeps the name of an atom that something outside the program relies on. The symmetry record describes the algorithm and what it finds in this repository.

Next: Inside the runtime

Part five

The system

System · 18

Inside the runtime

The runtime is Rust. One transition kernel applies every rule; two engines explore every future with it, and a direct path follows one.

ParseA seven-rule pest grammar builds a lossless syntax tree with byte spans.
LowerShorthand expands; particles, rules and scopes become a program.
CompileAtoms and rules are interned; rules with equal inputs share plans.
MatchIndexes and incremental joins deliver every binding.
ApplyOne kernel consumes, carries the remainder, introduces outputs and opens scopes.
CanonicalizeConfigurations equal up to renaming become one state; Laser names each by its parts.
ExploreLaser or the interpreter takes every event, plain mode every schedule without inference, and a direct path one run.
VerifyPrism compares the exact target and reports its verdict.

The kernel is language/evaluation.rs. The interpreter, in language/runtime.rs, explores every future, performs inference and records support: the events and derivations that justify each configuration. A configuration counts as reached only with support grounded in the start, so a cycle cannot justify itself. Direct paths live in language/path.rs, and Prism in language/prism.rs.

Laser, in language/laser.rs, is the engine the command line and every question explore with unless --engine interpreter asks for the interpreter. It names each configuration by its components instead of searching for the canonical form of the whole, remembers what each rule does to the components it touches, and carries matches back along events in rounds that run in parallel on every core. A closed exploration reaches the same configurations, events, support and verdicts on both engines, and Spectrum's answers name the same handles on either; every exhaustive photonic_test case runs on both and requires Laser to give the interpreter's answer whenever the interpreter closes. Laser is far faster once explorations grow: on six dials, 729 configurations and 13,122 events, one thread of Laser finishes more than four hundred times sooner than the interpreter. This book runs the interpreter, compiled to WebAssembly, in your browser; both engines close with the same answers. Laser is its contract.

--plain explores every schedule of plain events, those a configuration's own matches identify, without inference, to ask whether every order of rule applications reaches a result. Laser explores them, and so does --engine metal on the program's net of parts: on the GPU through Metal with the wave crate, or on the host where no GPU can. The metal engine keeps only counts, the configurations where runs end and whether a run can go on forever, so it answers explore and check alone. photonic_test(every = True) requires every plain schedule to end at a target.

Reports are identical with one, two or four workers; the tests check it. A budget defers work instead of dropping it, so a larger budget resumes. The command line and photonic_test share one set of default budgets. Occurrences count what a configuration's coherences hold and what its scopes hold as values, never the live rules a scope holds, which the scope limit bounds; scopes count the scopes a run opened, never the root. An open answer names the budget or limit that stopped it and the flag to raise.

BudgetWorkConfigurationsCoherencesOccurrencesScopesRecords
Command line and photonic_test2,000,0004,09664256642,000,000
This book, explored20,0001281625616100,000
This book, direct paths1,000,00032,7685122,0481,0242,000,000

The occurrence contract states loading, ownership and consumption precisely, and the runtime roadmap sets the priorities for runtime work.

Next: The repository

System · 19

The repository

Bazel is the only dependency. It downloads pinned Rust, LLVM, Node and every crate, and it checks formatting and lints on every build.

DirectoryResponsibility
frontendGrammar, parsing and lowering
languageExecution, the interpreter, Laser and its nets, canonical states and Prism
commandThe photonic command
spectrumSpectrum, the analyzer and debugger behind the command's questions and its MCP server, documented in document/spectrum.md
libraryThe standard library, in Photonic
programRunnable programs by subject, with their tests
theoremTheorems proved by execution
photonicBazel rules, assembly, launcher and the Prism test runner
bookThis webbook's styles, scripts and recorded runs
toolchainHermetic tools, checks and the WebAssembly engine
arithmeticGenerated arithmetic circuits and the infix encoder
benchmarkRuntime measurements
code, machine, translationLabel-free programs, exact flat execution and conversion to Photonic text
symmetryShapes, renamings and symmetries of programs
waveExploration of plain schedules on the GPU
metalThe Metal runtime binding that wave and gpu share
hashingThe shared hasher
randomSeeded randomness
network, gpu, learningThe program optimization learner, which is experimental
platformSupported platforms
documentContracts, the roadmap and dated runtime records

The learner

The learner is experimental. //learning:learning optimizes Photonic programs. It edits rules with a planner guided by a label-free transformer, keeps every example correct under every schedule, and minimizes parallel time and program size. solve finds the cheapest small flat program for a task, even one defined only by tests, and proves it optimal by exhausting every program that could beat it.

bazel run -c opt //learning:learning -- train --duration 3600
bazel run -c opt //learning:learning -- solve --input "$PWD/input.wave" --output "$PWD/output.wave"

The learner guide describes the objective, the search and the results. Build organization and continuous verification describe the build and the Buildkite pipeline.

Next: Grammar and glossary

Appendix

Reference

Reference · 20

Grammar and glossary

The whole grammar, every form and every term.

Grammar

module = { SOI ~ list ~ EOI }
list = { term? ~ ("," ~ term?)* }
term = { (atom | group | bracket | ".")+ }
group = { "(" ~ list ~ ")" }
bracket = { "[" ~ list ~ "]" }
atom = @{ (!("(" | ")" | "[" | "]" | "." | "," | WHITESPACE | SPACE_SEPARATOR | CONTROL | BIDI_CONTROL | "\u{200B}" | "\u{2060}") ~ ANY)+ }
WHITESPACE = _{ PATTERN_WHITE_SPACE | "\u{FEFF}" }

This is the whole grammar. Every balanced text is a program; only an unclosed or unmatched bracket, or a character no atom may hold, is an error. Five laws give it meaning, with no exceptions:

There are no keywords, operators or reserved words: Not, -> and unless are ordinary atoms. Whitespace is Unicode's pattern whitespace, which never changes, and U+FEFF, the byte order mark. An atom cannot hold any other space, such as U+00A0, nor a control character, U+200B, U+2060 or a direction control such as U+202E; joiners such as U+200D are part of it. Atoms compare by code point, without normalization.

Forms

FormExampleMeaning
AtomTrueOne occurrence
ParticleA.BOccurrences together, unordered
CoherencesA, BSeparate coherences
Empty coherence()One coherence with no occurrences
Rule[A] BConsume A, produce B with the remainder
Brackets sharing a term[A] [B] CConsume A.B, produce C
Join and split[A, B] (C, D)Consume from two coherences, produce two
ProgramA, [A] B, [B] CCoherences and live rules, in any order
Rule with no output[A]Consume A and produce nothing
Zero inputs[] AProduce a coherence from nothing
Any coherence[()] A, [(), ()] AMatch one or two coherences by position alone
Scope[A] (B, [B] C)Open a scope with a local rule
Scope with coherences[A] (B, C, [B, C] D)Open a scope holding two coherences
Scope in a scope[A] ((B, [B] C), [C] D)The inner scope returns to the outer one
Scope at the startA, (B, [B] C)The program opens the scope when it starts
Produced rule[Seed] ().([A] B)Produce the rule [A] B as a value
Matched rule[[A] B] CConsume the rule [A] B
FieldX.([Digit] 0)A role with its value
Rule alone in a coherence().([Digit] 0)A coherence holding only the rule
Shared prefixA.(B, C)A.B, A.C

Glossary

Atom
A run of characters without delimiters. It means nothing until rules use it.
Occurrence
One appearance of an atom or rule value, with its own identity.
Particle
An unordered multiset of occurrences in one coherence.
Coherence
An independent place where a particle lives.
Configuration
All coherences and live rules at one moment; a node of the graph.
Term
What sits between two commas. Its parts join, in any order; with brackets it is a rule.
Rule
Inputs in brackets and one output; a group gives several outputs. Also a value.
Event
One rule applied to one match; an arrow of the graph.
Plain event
An event that a configuration's own match identifies, without inference.
Schedule
One order in which events happen, from the start until the run stops. Plain mode explores every schedule of plain events.
Remainder
What a match leaves in its coherences; every output receives it.
Scope
A local place written like a program in parentheses: coherences, rules and scopes. A rule's output opens it when the rule fires, and the program opens its own when it starts. Its own rules return to the enclosing scope.
Frame
Where a scope lives in a configuration: its coherences, its rules and what it holds. The root frame is the program's. Answers show a scope's coherences after in f1: and name its frame s10.f1.
Capture
The scope a rule occurrence belongs to: the opening of the innermost scope written around it, or the program. Equal code with different captures gives different values, and a rule's input matches only rule values with its own capture.
Inference
Applying a rule to what a configuration can become, at the configuration itself.
Witness
The concrete occurrences an inferred match reached through evidence.
Deduction
The events that lead from an inferred event's configuration to the one where its rule matched.
Support
What justifies a configuration: events and derivations grounded in the start. Only a supported configuration counts as reached, so a cycle cannot justify itself, and answers mark what is unsupported.
Field
A one-rule value such as ([Digit] 0) that keeps a role with its value.
Target
A complete configuration, including live rules, that Prism looks for.
Exact target
A target read as a complete configuration, the way Prism reads one. --exact reads a claim's pattern that way, and --preserve adds every loaded root rule.
Verdict
Reached, unreachable or unknown.
Direct path
One execution, followed until it reaches the target or can go no further.
Budget
A limit on exploration. Exhausting it defers work and leaves answers unknown.
Closed, open
An exploration is closed when no work remains. One a budget stopped is open, and what it has not found is unknown; only a closed exploration can prove a target unreachable.
Shape
A program up to the names of its atoms. Programs with one shape differ only in their names.
Symmetry
A renaming of atoms that leaves a program unchanged.
Handle
A short name in Spectrum's answers: r2 a rule, s11 a configuration, e12 an event, s11.c0 a coherence, s11.o1 an occurrence and s10.f1 a frame.
Key
The name of one exploration, such as x895e0d34935dcf2a, which heads every answer about it. It hashes what the exploration depends on: the program, the mode, the engine and the budget. Over the Model Context Protocol a question can name the key instead of the program to ask more of the same exploration.
Nesting and expansion
The limits on source. Brackets and parentheses nest at most 128 deep, and lowering writes at most 1,000,000 units plus eight per byte of source, rule names included. The frontend refuses a program past either and says where.

Read next