# The circuit language

> The Stutr circuit language: C++-style declarations and operators, widths, settings, naming results, saved circuits as parts, and common errors.

## Write a circuit like a program

A Stutr circuit is a short program. Each line makes one part. If you have written C++, Java or Python it will look familiar: you declare things with a type and a name, and combine them with operators.

```stutr
// a half adder: adds two bits
Input a = 1;
Input b = 1;
Output sum = a ^ b;     // XOR
Output carry = a & b;   // AND
```

That is the whole circuit. `Input` and `Output` are parts, `a` and `b` are the names you chose, and `^` and `&` build an XOR gate and an AND gate for you. Press Run or click an input in the Editor tab, and the outputs update.

- End a line with `;`. It is optional, but with it you can put several statements on one line.
- `//` starts a comment that runs to the end of the line. `/* ... */` comments out several lines. `#` also starts a comment.
- Capital letters do not matter: `Input`, `input` and `INPUT` are the same word.
- A name uses letters, digits and underscores, cannot start with a digit, and can be used only once.

## Declaring parts

Declare any part the way you would create an object in C++: the part's word, then its width in angle brackets (optional), then a name, then the inputs in round brackets.

```stutr
Input<4> a = 5;       // a 4-bit input that starts at 5
Input<4> b = 9;
Adder<4> s(a, b);      // an adder whose inputs are a and b
Output<4> y = s;       // shows the sum
```

- `Word<bits> name(inputs);` works for every part. Inputs go in the order the part's pins are listed in the [parts reference](/docs/parts).
- Parts with no inputs (`Input`, `Constant`, `Button`...) take their value after an equals sign: `Input<4> a = 5;`. A clock or a button needs no value: `Clock ck;`.
- A part with a single input can also use an equals sign: `Output y = s;` means the same as `Output y(s);`.
- `<bits>` is the width, 1 to 16. Leave it off for 1 bit. When a part is declared from wires, it copies their width, so `Output y = s;` is already 4 bits wide.
- Leave a pin empty with `None`. An empty pin reads as 0.

## Operators

Write an expression and Stutr builds the parts for you. Every operator creates a gate or an arithmetic part, visible on the canvas.

```stutr
Input<4> a = 5;
Input<4> b = 9;
Output<4> total = a + b;       // 14
Output<4> masked = a & 0b0011;  // a plain number takes the other side's width
Output bigger = a > b;          // a comparison gives 1 bit
Output<4> doubled = a << 1;
Input pick = 1;
Output<4> chosen = pick ? a : b;
```

| Operator | Meaning | Part it builds |
| --- | --- | --- |
| `~a`  `!a` | every bit flipped | Not |
| `a & b`  `a \| b`  `a ^ b` | AND, OR, XOR of each bit | And, Or, Xor |
| `a && b`  `a \|\| b` | AND, OR for single bits | And, Or |
| `a + b`  `a - b`  `a * b` | add, subtract, multiply (the answer wraps to the width) | Adder, Subtractor, Multiplier |
| `a / b`  `a % b` | divide, remainder | Divider |
| `-a` | two's complement negative | Negator |
| `a == b`  `a != b` | equal, not equal (1 bit) | Comparator |
| `a < b`  `a > b`  `a <= b`  `a >= b` | compare as unsigned numbers (1 bit) | Comparator |
| `a << n`  `a >> n` | shift left or right by n places | Shifter |
| `sel ? x : y` | x when sel is 1, otherwise y | Mux |

- **Order:** the same as C. From strongest to weakest: `~ ! -`, then `* / %`, `+ -`, `<< >>`, `< > <= >=`, `== !=`, `&`, `^`, `|`, `&&`, `||`, and `? :` last. Use brackets whenever you are unsure.
- **Width:** the result is as wide as the widest wire in it. A plain number takes the width of the wire it meets. Adding wraps around: `15 + 1` in 4 bits is 0. To read the carry, use an `Adder` part (see below).
- Numbers can be written as `12`, `0xC`, `0b1100`, `true` (1) and `false` (0).

## Naming results

Give any result a name with `Wire`, or with a plain `name = expression` line like Python. The part keeps that name on the canvas, and you can use it again further down.

```stutr
Input<4> a = 5;
Input<4> b = 9;
Wire<4> total = a + b;   // the adder is now called total
masked = total & 7;       // Python style works too
Output<4> y = masked;
```

Use `Wire` when the result will be used more than once. The name must be new: you cannot declare the same name twice.

## Picking out pieces

```stutr
Input<4> a = 15;
Input<4> b = 1;
Adder<4> s(a, b);
Output<4> sum = s.sum;    // an output of a part, by name
Output carry = s.carry;
Output lowest = a[0];     // one bit of a wider wire
```

- A part with several outputs lists their names in the parts reference. Write `s.carry`, or by number, `s[1]`.
- `a[2]` picks bit 2 of a wider wire (bit 0 is the lowest). Stutr adds a Splitter for you.
- You can use a part directly inside an expression: `Output carry = Adder<4>(a, b).carry;`

## Order, and loops that feed back

A line may use a part that is declared further down. That is how you build a circuit whose output feeds back into itself:

```stutr
Clock ck;
Wire d = ~ff.q;          // ff is declared below, and that is fine
DFlipFlop ff(d, ck);
Output q = ff.q;
```

This flips `q` on every clock tick. Feeding a wire back without a flip-flop or register in the loop makes a combinational loop, which reads as floating.

## Settings

Some parts have extra settings, written as `key=value` after the inputs:

```stutr
Input<4> a = 1;
Input<2> n = 1;
Input<6> x = 0;
Input<6> y = 0;
Input<3> d = 5;
Input we = 1;
Clock ck;

ROM<4> r(a, addr=4, data="3 a f");
Shifter<4> sh(a, n, mode="rr");
LEDScreen<3> sc(x, y, d, we, None, ck, width=64, height=64, color="#3be0ff");
```

| Setting | On which parts | What it does |
| --- | --- | --- |
| `value` | constant | The fixed number |
| `to` | bit extender, pull resistor | Extender: the output width. Pull resistor: `"0"` or `"1"` |
| `fill` | bit extender | `"zero"`, `"one"` or `"sign"` |
| `mode` | shifter | `ll`, `lr`, `ar`, `rl` or `rr` |
| `find` | bit finder | `low1`, `high1`, `low0` or `high0` |
| `stages` | shift register | How many stages |
| `addr` | RAM, ROM | Address width in bits |
| `data` | ROM | Contents as hexadecimal words separated by spaces |
| `rows` | LED matrix | Number of rows |
| `width`, `height` | LED screen | Size in pixels, 1 to 2048 each |
| `color` | LED screen | LED color as `"#rrggbb"` |
| `tag` | tunnel | Name that connects tunnels together |
| `kind` | transistor | `"n"` or `"p"` |
| `text` | text note | The words |

Every part in the [parts reference](/docs/parts) lists exactly which settings it accepts.

## Using a saved circuit as a part

Any circuit you have saved in Projects can be used as a part in another circuit. Its name becomes the word you write, in lowercase with underscores (a project called "Half Adder" is `half_adder`). The input and output pins inside it become the part's pins, in the order they appear in its code, with the names you gave them.

```text
// half_adder is a saved circuit with inputs a, b and outputs sum, carry
Input x = 1;
Input y = 1;
half_adder u(x, y);
Output s = u.sum;
Output c = u.carry;
```

- Refer to a chip's outputs by the names of its output pins: `u.sum`, `u.carry`.
- A chip keeps its own memory: a counter or flip-flop inside it holds its value between clock edges.
- A chip can contain other chips, but never itself.
- Inside a chip, use an input pin for the clock, not a clock part, so the outer circuit controls the timing.
- Using chips as parts is part of the Pro plan. Circuits that already use them still open and run on any plan.

## The older style still works

Earlier versions of Stutr wrote one part per line as `name = part<bits>(inputs)`. That still works, and you can mix both styles in one circuit. When you change a circuit on the canvas, the code is rewritten in the style on this page.

```stutr
// the same circuit in the older style
Input<4> a = 5;
Input<4> b = 9;
Adder<4> s(a, b);
Output<4> y = s;
```

In the older style, a part is exactly as wide as written (no width is copied from the wires) and only the part's own setting words are used. Every part also has older spellings, listed in the table below.

| Part | Word | Older words that still work |
| --- | --- | --- |
| Pin (input) | `Input` | `in` |
| Clock | `Clock` | `clk` |
| Constant | `Constant` | `const` |
| Power | `Power` | - |
| Ground | `Ground` | `gnd` |
| Probe (output) | `Output` | `out` |
| Splitter | `Splitter` | `split` |
| Combiner | `Combiner` | `merge` |
| Tunnel | `Tunnel` | - |
| Pull resistor | `PullResistor` | `pull` |
| Transistor | `Transistor` | `trans` |
| Transmission gate | `TransmissionGate` | `tgate` |
| Bit extender | `BitExtender` | `ext` |
| NOT gate | `Not` | - |
| Buffer | `Buffer` | `buf` |
| AND gate | `And` | - |
| OR gate | `Or` | - |
| NAND gate | `Nand` | - |
| NOR gate | `Nor` | - |
| XOR gate | `Xor` | - |
| XNOR gate | `Xnor` | - |
| Odd parity | `OddParity` | `odd` |
| Even parity | `EvenParity` | `even` |
| Controlled buffer | `ControlledBuffer` | `cbuf` |
| Controlled inverter | `ControlledInverter` | `cinv` |
| Multiplexer | `Mux` | - |
| Demultiplexer | `Demux` | - |
| Decoder | `Decoder` | `dec` |
| Priority encoder | `PriorityEncoder` | `penc` |
| Bit selector | `BitSelector` | `bsel` |
| Adder | `Adder` | `add` |
| Subtractor | `Subtractor` | `sub` |
| Multiplier | `Multiplier` | `mul` |
| Divider | `Divider` | `div` |
| Negator | `Negator` | `neg` |
| Comparator | `Comparator` | `cmp` |
| Shifter | `Shifter` | `shift` |
| Bit adder | `BitAdder` | `badd` |
| Bit finder | `BitFinder` | `bfind` |
| D flip-flop | `DFlipFlop` | `dff` |
| T flip-flop | `TFlipFlop` | `tff` |
| J-K flip-flop | `JKFlipFlop` | `jkff` |
| S-R flip-flop | `SRFlipFlop` | `srff` |
| Register | `Register` | `reg` |
| Counter | `Counter` | `ctr` |
| Shift register | `ShiftRegister` | `shreg` |
| Random generator | `RandomGenerator` | `rnd` |
| RAM | `RAM` | - |
| ROM | `ROM` | - |
| Button | `Button` | `btn` |
| Joystick | `Joystick` | `joy` |
| Keyboard | `Keyboard` | `keyb` |
| LED | `LED` | - |
| 7-segment display | `SevenSegment` | `seg7` |
| Hex digit display | `HexDisplay` | `hex` |
| LED matrix | `LEDMatrix` | `matrix` |
| TTY (terminal) | `TTY` | - |
| LED screen | `LEDScreen` | `screen` |
| Text note | `Text` | - |

## Where parts go

Code has no coordinates. A part keeps its place on the canvas as long as its name and type stay the same. New parts are placed automatically, left to right by how many steps they are from an input. Drag them wherever you like. Moving things on the canvas never changes the code. Parts Stutr creates from an operator are named `_and1`, `_add2` and so on.

## When something is wrong

If a line cannot be read, the bar under the code shows the line number and what is wrong, and the canvas keeps the last circuit that worked. Fix the line and the canvas updates. Messages you may see:

| Message | What it means |
| --- | --- |
| `unknown name "b". Declare it first, for example: Input b = 0;` | You used a name that no line declares. |
| `unknown part "Foo"` | There is no part with that word. Check the spelling against the parts reference, or start typing to see suggestions. |
| `name "a" is used twice` | Two parts have the same name. |
| `And takes 2 inputs` | You gave a part more inputs than it has pins. |
| `And has 2 inputs. Write: And g(a, b);` | A part with several inputs needs the round-bracket form. |
| `s has no output called "foo". Its outputs are: sum, carry` | A part's output name is misspelled. |
| `bit 7 does not exist` | You picked a bit beyond the wire's width. |
| `Adder has no setting "x"` | That part does not accept that setting. |
| `I don't understand the character '@'` | A character that is not part of the language. |
| `expected ')' but found …` | A bracket is missing or in the wrong place. |
