QuantumVM

QuantumVM

An OpenQASM 3.0 language server and runtime, written in Rust.

00 The gap

The tooling problem.

→
OpenQASM is the assembly language of quantum computing — IBM, Amazon Braket and Rigetti all speak it.
→
But most people write it inside Python, as strings. No types. No autocomplete. No go-to-definition.
→
You find out a gate takes the wrong number of qubits after you've queued the job.
the usual workflow
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 5)   # ← no qubit 5
#   discovered at runtime,
#   somewhere in a stack trace
01 What it is

Two binaries.

quantumvmruntime

Parses, type-checks and runs a .qasm file. Prints what the program measured.

$ quantumvm bell.qasm
qasm-lsplanguage server

The same front end, wired into your editor instead of a terminal.

VS Code · JetBrains · anything LSP

~10,200 lines of Rust. Lexer, parser, type checker and interpreter all hand-written — no parser generator, no Python anywhere.

02 Sixty seconds of physics

Enough quantum to follow along.

01
A qubit is a bit that holds a blend of 0 and 1 until you look at it.
02
Gates are the operations. Every one of them is reversible — which will matter later.
03
Measuring forces the blend to pick a side, and the pick is random.
04
The catch: simulating n qubits means tracking 2ⁿ numbers. 24 qubits is 16.7 million of them.

That last one is why this is written in Rust and not Python. A 24-qubit, 47-gate program runs in 1.3 seconds, using 2.8 cores' worth of CPU.

03 Demo

A Bell state.

bell.qasm
OPENQASM 3.0;

qubit[2] q;
output bit[2] result;

h  q[0];
cx q[0], q[1];

result[0] = measure q[0];
result[1] = measure q[1];
eight consecutive runs
→ 00 → 00 → 11 → 00 → 00 → 11 → 00 → 00

Random every time — but the two bits never disagree.

You will not see 01 or 10. Not in eight runs, not in eight million. Nobody coded that rule — it is simply what entanglement is.

04 Architecture

The pipeline.

01
Lexer
chars → tokens
spans kept for every one
02
Parser
recursive descent
error recovery, no bail-out
03
Type checker
inference + coercion
errors, warnings, hints
04
Interpreter
tree-walking
classical + quantum
05
Statevector
the simulation
parallel across cores

Stages 01–03 are exactly what the language server runs. Diagnostics aren't a separate linter — they're a by-product of compiling.

05 Stage 01 Lexer

Source to tokens.

bell.qasm
source
1 2
qubit[2] q; h q[0];
→
lexer output15 tokens
TypeDef(Qubit)        @ 0:0  len 5
Symbol(LBracket)     @ 0:5  len 1
Literal(Integer(2))  @ 0:6  len 1
Symbol(RBracket)     @ 0:7  len 1
Identifier("q")     @ 0:9  len 1
Symbol(Semicolon)    @ 0:10 len 1
…

Notice the @ line:col len on every single token. That's the span — and it is the reason every later stage can point back at your source.

06 Stage 02 Parser

Tokens to a tree.

token stream
Identifier("h")
Identifier("q")
Symbol(LBracket)
Literal(Integer(0))
Symbol(RBracket)
Symbol(Semicolon)
→
parser outputAST
GateCall {
    name: "h",
    modifiers: [],
    params: [],
    qubits: [ IndexedIdent {
        name: "q",
        indices: [ Expr(Int(0)) ],
        span: Span { line: 1, col: 2 }
    } ]
}

Recursive descent, written by hand. On a syntax error it doesn't stop — it skips to the next statement and keeps building, so an editor always has a tree to work with.

07 Aside

Expressions and statements.

StmtKinddoes something
GateCall { name, modifiers, params, qubits }
ClassicalDecl { ty, name, init }
Assign { target, op, value }
If { cond, then, else_ }
For { var, ty, iter, body }
Return(Option<Expr>), Break, Continue,
… 24 variants

No value. You run it for its effect.

ExprKindhas a value
Int(i64), Float(f64), Bool(bool),
Ident(String), IndexedIdent(…),
Binary { op, lhs, rhs }
Call { name, args }
Cast { ty, expr }
Measure(GateOperand),
… 15 variants

Evaluates to something, and nests inside other expressions.

which is which, in practice
h q[0];                    // statement — flips amplitudes, gives nothing back
result[0] = measure q[0];  // measure is an expression — it has a value
so this can't parsereal output
5 │ r = h q[0]; │ ┬ │ ╰── expected ';', found identifier

The bridge between them is ExpressionStatement(Expr) — an expression evaluated purely for its side effect, with the value thrown away.

08 Stage 03 Type checker

Checking types.

mismatch.qasm
1 problem
1 2 3 4
OPENQASM 3.0; qubit q; int[32] x = q;
what the checker knows by line 4
q  : qubit          // declared 3:6
x  : int[32]        // declaring…

A qubit is not a number, and no coercion rule turns one into the other. Rejected before anything runs.

The same pass does inference, bit widths, implicit coercions and gate arity — and records every symbol's definition and uses, which is the data rename and find-references query later.

09 Stage 04 Interpreter

Running a gate call.

the statement from stage 02
GateCall {
    name: "h",
    modifiers: [],
    params: [],
    qubits: [ q[0] ]
}

A name, some modifiers, some parameters, and some operands. The interpreter has to turn all four into something the simulator can apply, plus a list of qubit indices.

fn interpret_gate_callfour jobs
01 // params are expressions, not numbers
   params.iter().map(evaluate_expression)
   → Vec<f64> = []

02 // q[0] is a name — which qubit is it?
   self.resolve_qubits(q)
   → Vec<Vec<usize>> = [[0]]

03 // what is "h"?
   self.functions.get("h")
   → a gate defined in stdgates.inc

04 // turn it into numbers
   self.resolve_gate(name, &func, &params)
   → ResolvedGate::SingleQubit(Matrix2)

Step 04 is the odd one. h has no implementation in the Rust at all. To get one, the interpreter runs the gate's own QASM body and records what it does — then caches the result, keyed by name and parameters.

10 Stage 05 Statevector

A big array of numbers.

still the same GateCallh q[0]
GateCall { name: "h", qubits: [ q[0] ] }
amplitudes: Vec<Complex<f64>>   // one per slot

Stage 04 handed over what h does and which qubit — qubit 0.

one slot per possible answerslots = 2ⁿ
00slot 0
01slot 1
10slot 2
11slot 3
2 qubits → 2² = 4 slots      24 qubits → 2²⁴ = 16,777,216

Every qubit you add doubles the array — the whole difficulty of simulating quantum computers, in one line.

h works two slots at a time
00and01
10and11

q[0] is the right-hand bit, so h pairs up the answers that differ only there. It never mixes 00 with 10.

where the 50% comes fromstarted at 00
numberchance
00
0.707
50%
01
0.707
50%
10
0
0%
11
0
0%
slot 0 started at 1; h split it evenly → 0.707 each
chance = the number squared → 0.707 × 0.707 = 0.5

The two pairs never touch, so both updates run at once — which is how a gate over 16.7 million slots still finishes fast.

11 Diagnostics

Three kinds of error.

stage 02parse
Unexpected token ╭─[a.qasm:3:11] │ 3 │ qubit[2] q │ ┬ │ ╰── expected ';', │ found newline ───╯
stage 03type
Type mismatch in variable declaration 'x': expected int[32], found qubit ╭─[b.qasm:5:1] │ 5 │ int[32] x = q; ───╯
stage 05runtime
Index 5 out of bounds (valid range: 0 to 1) ╭─[c.qasm:5:5] │ 5 │ h q[5]; ───╯

Same shape every time, because they all come from the same spans. Only the third one needs the program to actually run — the goal is to keep moving errors leftward.

12 In the editor

Errors while you type.

bell.qasm
qasm-lsp
1 2 3 4 5
OPENQASM 3.0; include "stdgates.inc"; qubit[2] q; int[32] x = q; Type mismatch in variable declaration 'x' expected int[32], found qubit qasm-lsp · QuantumVM
Problems
✕Type mismatch in variable declaration 'x'bell.qasm 5:1

No build. No run. No queue. The squiggle appears while you type.

It is the exact same type checker from stage 03 — the only difference is that the diagnostic gets serialized to JSON and sent to the editor instead of printed to a terminal.

Which raises the obvious question: how does an editor that has never heard of OpenQASM know how to draw that?

13 The Language Server Protocol

What a language server is.

the whole idea

Your editor launches it as a subprocess and talks to it over stdin and stdout in JSON. The editor knows nothing about the language; the server knows nothing about the editor.

a conversation
editor → "this file changed, here's the text" server → "error at line 5, column 1" editor → "ctrl-space at line 12, column 4" server → "h, cx, rx, ry, measure…"

Before this existed, every editor needed its own plugin for every language — ten languages across five editors meant fifty half-finished implementations. Now it's one server, and every editor gets it.

qasm-lsp answers10 questions
diagnostics
go-to-definition
find references
hover
completions
signature help
rename
document symbols
semantic tokens
highlight

Every one of those is a query against data stages 01–03 already built. Hover reads the type checker's table. Rename reads the reference registry.

Built on tower-lsp and tokio; open files live in a DashMap and every keystroke re-runs the front end.

14 Editor support

VS Code and JetBrains.

VS Codeextension

QASM Language Support — finds qasm-lsp and launches it for you.

github.com/wiji1/QuantumVM-VSCode

JetBrainsplugin

Same binary, same features, wired into the IntelliJ platform.

github.com/wiji1/QuantumVM-Jetbrains

Both plugins are thin — they start a process and forward messages. Everything they can do, any LSP-capable editor gets for free.

15 Testing

The test suite.

Each case is a real .qasm program plus the assertion that pins its result. Most of them have nothing to do with quantum at all.

nested_loops.qasmloops
output int[32] sum;
sum = 0;

for int[8] i in [0:3] {
    for int[8] j in [0:2] {
        sum += 1;
    }
}
assert_int_output(&r, "sum", 12);

Ranges are inclusive, so that's 4 × 3, not 3 × 3. Exactly the off-by-one a test pins and a comment doesn't.

modulo_negative.qasmsemantics
output int[32] result1;
output int[32] result2;

int[32] a = -7;
int[32] b = 3;

result1 = a % b;
result2 = (-10) % 4;
assert_int_output(&r, "result1", -1);
assert_int_output(&r, "result2", -2);

Languages disagree here — Python says 2, C says -1. The test is where that choice is written down.

const_reassignment.qasmmust fail
const int[32] N = 10;
N = 20;

// Error: Cannot assign
//        to constant: N
assert_type_error(&r);

Plenty of cases assert the program is rejected. A type checker that accepts everything passes every happy-path test.

111 cases across four suites — classical ops, control flow, quantum ops, error handling — in under a tenth of a second. Every push runs them, plus clippy -D warnings.

16 Shipping it

Packaging and CI.

releasecargo-dist

Tag a commit and it builds five target triples, cuts a GitHub release, and publishes a Homebrew tap — plus shell and PowerShell installers.

aarch64 + x86_64 · macOS · Linux · Windows
every pushCI

Tests and clippy -D warnings on every PR — lints are errors, not suggestions. Release builds verified on all three OSes.

$ brew install wiji1/tap/quantumvm

Maybe 5% of the work, and the reason anyone other than me can actually run it.

17 Where it stands

By the numbers.

10.2k
lines of Rust
37 modules
111
tests
all passing
10
LSP features
one server
5
platform targets
auto-released

Working today

full simulation · custom gate definitions · gate modifiers
loops, switch, break/continue · functions · arrays & slicing
const & type coercion · input/output declarations

Next

a --shots flag with histogram output
noise models · circuit visualization
incremental re-parsing in the language server

Thanks.