Skip to main content
N/M ReferenceLanguage v0.2.0 · Preview

N/M language documentation

The preview N/M product reference: a stable 0.1 parser and statevector core, usable workspace and tooling surfaces, and separately versioned experimental 0.2 capabilities that remain explicit opt-ins.

Versioned capability matrix

Every status below comes directly from the language version manifest used by the CLI, language server, packages, and this documentation. Stable means covered by the current compatibility contract; preview may evolve; experimental requires explicit evaluation before production use.

Stable2
Preview35
Experimental21
Capability and Release Center

N/M reference

Capabilities

A versioned compatibility view of the parser, runtimes, formatter, language server, compiler pipeline, package formats, and hardware boundary.

Stabilizer runtime

Run the frozen Clifford/global-phase tableau contract up to 100 qubits with explicit fallback, sampling, diagnostic, and performance boundaries.

Target-native lowering

Lower every supported gate to a published target basis, verify unitary semantics where bounded, and fail closed when no complete decomposition exists.

Calibrated placement

Validate bounded target calibration documents, select deterministic connected physical qubits, and reject unroutable workloads before lowering.

Target scheduling

Build bounded integer-nanosecond ASAP schedules, preserve source order and physical-resource dependencies, and fail closed on timeline drift.

Target capabilities

Negotiate an exact target profile, native gate set, connectivity topology, and bounded reference error budget with deterministic compiler evidence.

OpenQASM 3

Export a frozen OpenQASM 3.0 subset, verify syntax with the official reference grammar, and preserve N/M-only semantics in a versioned fail-closed sidecar.

Multi-file workspaces

Define a versioned workspace manifest, index imports without recursive-stack risk, and diagnose duplicate, missing, cyclic, oversized, or unsafe workspace inputs.

Workspace snapshots

Create, validate, share, and inspect deterministic read-only multi-file source bundles with bounded reproducibility metadata.

Local workspace store

Persist bounded projects in IndexedDB with explicit migrations, tamper-evident integrity, typed storage failures, and conflict-safe revisions.

Source debugger

Resolve verified breakpoints through one-based source maps, cancel immutable or Worker sessions, inspect bounded timelines, and record the same contract through the CLI.

Language Server

Use a bounded JSON-RPC lifecycle, stale-version-safe document sync, reusable 5,000-document workspace indexes, and byte-identical Core, standalone, and VS Code behavior.

VS Code extension

Install the N/M extension, test your first program, step through the debugger and resolve common problems.

Release notes

Review N/M product versions, published VS Code extension versions, installation channels and changes.

Module visibility

Negotiate public/private workspace exports while keeping private declarations local and stable 0.1 declarations legacy-public.

Property assertions

Negotiate seeded finite-shot tolerances, inclusive observable ranges, explicit global-phase equivalence, and auditable property counterexamples.

Typed classical values

Negotiate immutable Int, Float, fixed arrays, explicit measurement conversions, deterministic runtime evidence, and fail-closed numeric bounds.

Function results

Negotiate typed Result values for main, exact ok payloads, bounded symbolic program errors, and explicit separation from engine failures.

Quantum job API

Submit, poll, and cancel bounded N/M jobs through a versioned carrier, opaque ownership scope, atomic idempotency, terminal state invariants, and explicit production gates.

MCP server

Connect agents to seven versioned local N/M tools with strict protocol negotiation, hostile-client validation, bounded carriers and byte-identical Core/stdio behavior.

Training

Define a bounded train block beside the quantum model, run deterministic local optimization, and inspect final parameters, cost history, convergence, output, and trace evidence.

QML numeric core

Use versioned training, loss, SPSA, and adjoint contracts with finite inputs, exact evaluation accounting, deterministic surface parity, and explicit numerical failure codes.

QML datasets

Inspect bounded embedded dataset schemas, permanent readers, disjoint train/validation/test splits, held-out validation evidence, and explicit provenance boundaries.

QML ML library

Use seven frozen QML circuits and observables through exact-version imports, fail-closed resolution, verified package identities, and Core/CLI/Worker semantic parity.

QML algorithms

Build checked fidelity kernels and weighted MaxCut QAOA runs with finite inputs, deterministic Worker parity, exact evaluation accounting, and explicit local workload limits.

QML product surfaces

Run cancellable training, bounded trainability diagnostics, and fair optimizer benchmarks with versioned lifecycle, numeric, timing, and evaluation evidence.

QML artifacts

Export, verify, migrate, import, evict, and clear bounded local QML artifacts with strict schemas, canonical integrity, and explicit privacy policy.

CLI

Operational commands for creating, checking, testing, running, packaging, exporting, transpiling, and sharing reproducible N/M workspaces.

Verified copilot

Generate bounded local N/M templates from natural-language intents, then inspect parser, semantic, runtime, repair, capability, cost, and privacy evidence before opening the code.

Grounded tutor

Ask questions about N/M source and receive explanations tied to exact source or module lines and diagnostics. Suggested code is checked for compilation only; neither code nor training is executed.

Classroom

Inspect the versioned assignment, public starter, private behavioral-check, weighted rubric, idempotent attempt, role, history, and aggregate analytics boundaries.

Diagnostics

Search stable parser, type, semantic, runtime, assertion, workspace, calibration, and compiler diagnostic codes with actionable fixes.

Packages

Search versioned packages, inspect source integrity and attestations, install exact versions, and follow the signed release lifecycle.

Standard library

Built-in circuit and observable modules rendered from the same registry used by imports, runtime expansion, exports, and editor tooling.

Turkish source

Preferred Turkish keywords, portable ASCII aliases, source-preserving formatting behavior, and a starter program verified by the runtime test suite.

Turkish source surface

Add @dil("tr") to use preferred Turkish action and control-flow keywords. The parser normalizes them token by token, while the CST formatter preserves the source language, comments, imports, and block structure. ASCII aliases such as olc, eger, sifirla, and dogrula remain accepted for keyboard portability.

usekullan
measureölç
resetsıfırla
ifeğer
elsedeğilse
forher
repeattekrarla
assertdoğrula
paramparametre
traineğit
objectivehedef
optimizereniyileyici

Turkish N/M starter

Open in Playground
@dil("tr");module turkce_bell; fn main() {  let q = qreg[2];  H(q[0]);  CNOT(q[0], q[1]);  doğrula entangled(q[0], q[1]);  let sonuc = ölç(q[0]);  eğer (sonuc == 1) { X(q[1]); }  return sonuc;}

Turkish source

Module and entry point

Beginner examples use a module declaration and fn main() as the executable entry point.

Quantum registers

Use qreg[n] to allocate a small register and index qubits with q[0], q[1], and so on.

Gate calls

The playground subset supports H, X, Y, Z, S, T, CNOT, CZ, SWAP, CCNOT, Ry, Rz, and the controlled rotations CRy, CRz, and CP.

Measurement

measure(q[i]) and measure X/Y/Z(q[i]) convert a qubit state into a sampled classical result and collapse the simulated state.

Runnable starter example

Open in Playground
module bell_state; fn main() {  let q = qreg[2];  H(q[0]);  CNOT(q[0], q[1]);  let first = measure(q[0]);  let second = measure(q[1]);  return (first, second);}

Reading basis bitstrings

The Playground prints q[0] as the rightmost bit: q[n−1] … q[0]. Starting from zero, X(q[0]) produces |01> for qreg[2] and |001> for qreg[3]. This display convention does not change gate targets.

Asymmetric two-qubit example: P(01) = 1

Open in Playground
module bit_order;fn main() {  let q = qreg[2];  X(q[0]);  return q;}

CLI workflow

Initialize, format, lint, test, execute, explain, package, estimate, and export N/M programs from the same toolchain used by the Playground.

nm run main.nm --sweep sweep.json --experimental-parameter-groups --json
nm check main.nm --json
nm run main.nm --shots 1024 --json
nm debug main.nm --breakpoint 6 --json
nm fmt main.nm --check
nm lint main.nm --strict
nm test main.nm --experimental-property-assertions --json
nm explain main.nm --json
nm transpile main.nm --target superconducting --calibration calibration.json --json
nm estimate main.nm --ftqc --budget nm-budget.json
nm export main.nm --to qasm3 --strict --json
nm benchmark main.nm --optimizers gd,adam --steps 8 --csv
nm checkpoint create main.nm --steps 8
nm checkpoint resume training.checkpoint.json --additional-steps 8
nm checkpoint model training.checkpoint.json --name resumed-model
nm init main.nm
nm package build main.nm
nm package validate package.json
nm package list --json
nm package inspect std.bell@0.1 --json
nm package install std.bell@0.1 --output std_bell.nm --json
nm package sign release.json --output release.signed.json --json
nm package verify release.signed.json --json
nm workspace snapshot main.nm
nm workspace share main.nm
nm workspace validate workspace.snapshot.json --json
nm lock main.nm
nm lock main.nm --lock nm-lock.json --json

Formatting writes the file by default; use --check for a non-mutating CI gate. init refuses to overwrite unless --force is provided.

Multi-file workspace imports

Declare reusable circuits, observables, and constants in another .nm module, then import them explicitly, for example with use workspace.reusable_bell;. The import graph scopes completion, definition, references, signature help, diagnostics, and rename.

Multi-file N/M workspace

// reusable_bell.nmmodule reusable_bell;circuit prepare_bell(data: QReg<2>) {  H(data[0]);  CNOT(data[0], data[1]);} // bell_app.nmmodule bell_app;use workspace.reusable_bell;fn main() {  let q = qreg[2];  prepare_bell(q);  return q;}

The CLI indexes sibling .nm files recursively or honors the sourceRoots in nm-workspace.json. The VS Code extension keeps up to 5,000 workspace files indexed, including files that are not open. Missing, duplicate, and cyclic modules produce NM-WORKSPACE diagnostics. workspace snapshot/share creates a deterministic read-only artifact with source and run fingerprints.

Error codes

NM-PARSE-002

Missing module declaration

The file must start with a module declaration such as module bell_state;
Add a module name before fn main().
NM-PARSE-003

Missing fn main

The playground executes a single fn main() entry point.
Add fn main() { ... } around executable statements.
NM-TYPE-002

Invalid qubit reference

A gate or measurement points to a qreg index that was not allocated.
Keep indexes inside the declared qreg size, for example q[0] and q[1] for QReg<2>.
NM-TYPE-005

QReg size mismatch

The type size and allocation size disagree.
Use matching syntax such as let q: QReg<2> = qreg[2];
NM-TYPE-006

Invalid rotation angle

Ry/Rz/CRy/CRz/CP received an angle expression that could not be evaluated.
Use a number, PI, a declared constant, or arithmetic such as Ry(q[0], PI / 2);
NM-SEM-001

Duplicate qubit operand

A multi-qubit gate uses the same physical qubit more than once.
Use distinct qubits for every operand, for example CNOT(q[0], q[1]) instead of CNOT(q[0], q[0]).
NM-SEM-002

Gate after measurement

A gate touches a qubit after direct measurement collapsed it.
Use reset before more quantum gates, move the measurement later, or add @semantics("strict"); if this should block execution.
NM-SEM-003

Unused qubit

A qreg allocation contains a qubit that no gate, measurement, expectation, reset, or encode step uses.
Remove the spare qubit or include it in the intended circuit.
Diagnostics

Language reference

The gates, controlled rotations, and annotations the browser runtime understands today.

Gates

H, X, Y, Z, S, TH(q[0])

Single-qubit gates: superposition, Pauli flips, and phase gates.

Sdg, TdgSdg(q[0])

Inverse phase gates S† and T† for uncompute.

Rx, Ry, RzRx(q[0], PI / 2)

Parameterized single-qubit rotations; angles accept PI and arithmetic.

P, U, GPhaseU(q[0], PI / 2, 0, PI)

Universal phase/global phase gates for OpenQASM-compatible circuits.

CNOT, CZCNOT(q[0], q[1])

Two-qubit controlled-X and controlled-Z.

CY, CHCY(q[0], q[1])

Controlled-Y and controlled-Hadamard.

Language features

constconst theta: Angle = PI / 4;

Declare numeric/angle constants reusable as rotation arguments.

const : Int (size-generic)const n: Int = 4;

Compile-time integer, substituted into QReg<n>, qreg[n], for ranges, q[n-1], and repeat n.

param (trainable)param w: Angle = 0.1;

A trainable rotation angle optimized with automatic adjoint gradients when eligible and parameter-shift fallback otherwise.

param Angle[N]param theta: Angle[4] = [0.1, 0.2, 0.3, 0.4]; Ry(q[0], theta[0]);

Vector trainable parameters expand into indexed scalar params for compact variational ansatz layers.

std library importsuse ml.vqc_layer; use chemistry.h2_minimal;

Import built-in circuit templates and observables, including ml.* variational, reupload, entangler, IQP, and ZZ helpers; they expand before runtime and export.

register slicesH(q[0..3]); bell(q[1..2]);

Broadcast single-qubit gates across a register range or map circuit templates onto a selected contiguous slice.

Standard library registry

Built-in circuit templates and observable packages are rendered from the same registry the parser uses for use statements.

Circuit helpers

std.bellcircuitv0.12 qubits

bell

Two-qubit Bell-pair preparation.

use std.bell; bell(q);
exports bell#entanglement#starter#two-qubit
std.ghzcircuitv0.13 qubits

ghz

Three-qubit GHZ preparation.

use std.ghz; ghz(q);
exports ghz#entanglement#multi-qubit#state-preparation
std.hadamard_statecircuitv0.11 qubits

hadamard_state

Single-qubit |+> state preparation for superposition experiments.

use std.hadamard_state; hadamard_state(q);
exports hadamard_state#superposition#starter#single-qubit

Algorithm circuits

algorithms.grover2circuitv0.12 qubits

grover2

Two-qubit Grover iteration with a |11> phase oracle and diffusion step.

use algorithms.grover2; grover2(q);
exports grover2#search#grover#amplitude-amplification
algorithms.phase_kickbackcircuitv0.12 qubits

phase_kickback

Prepare a control superposition and a |-> ancilla, then demonstrate CNOT phase kickback.

use algorithms.phase_kickback; phase_kickback(q);
exports phase_kickback#phase#oracle#controlled-gate
algorithms.deutsch_jozsa2circuitv0.22 qubits

deutsch_jozsa2

Two-qubit Deutsch-Jozsa circuit for a fixed balanced f(x)=x oracle.

use algorithms.deutsch_jozsa2@0.2; deutsch_jozsa2(q);
exports deutsch_jozsa2#oracle#interference#deutsch-jozsa#algorithm-pack-0.2

Error-correction circuits

qec.perfect5_codecircuitv0.49 qubits

perfect5_code

Prepare the logical |0> state of the [[5,1,3]] perfect code on five data qubits while reserving four syndrome qubits for the caller.

use qec.perfect5_code@0.4; perfect5_code(q);
exports perfect5_code#qec#perfect-code#stabilizer#feed-forward#algorithm-pack-0.4
qec.steane7_codecircuitv0.413 qubits

steane7_code

Prepare the logical |0> state of the [[7,1,3]] Steane code on seven data qubits while reserving six syndrome qubits for the caller.

use qec.steane7_code@0.4; steane7_code(q);
exports steane7_code#qec#steane-code#stabilizer#feed-forward#algorithm-pack-0.4
qec.surface_d3_patchcircuitv0.417 qubits

surface_d3_patch

Prepare a logical |0> state for the fixed [[9,1,3]] rotated surface-code patch while reserving eight syndrome qubits.

use qec.surface_d3_patch@0.4; surface_d3_patch(q);
exports surface_d3_patch#qec#surface-code#distance-three#stabilizer#feed-forward#algorithm-pack-0.4

State preparation circuits

states.ghz100circuitv0.4100 qubits

ghz100

Prepare the fixed 100-qubit GHZ stabilizer state with one Hadamard and a 99-CNOT chain.

use states.ghz100@0.4; ghz100(q);
exports ghz100#state-preparation#ghz#stabilizer#100-qubit#algorithm-pack-0.4
states.graph_state100circuitv0.4100 qubits

graph_state100

Prepare the fixed 100-node line graph state with textual exact adjacency available in the stabilizer scale view.

use states.graph_state100@0.4; graph_state100(q);
exports graph_state100#state-preparation#graph-state#stabilizer#100-qubit#algorithm-pack-0.4

Nonlocality witnesses

nonlocality.mermin_ghz3circuitv0.43 qubits

mermin_ghz3

Prepare a three-qubit GHZ state for the exact local XXX/XYY/YXY/YYX Mermin witness.

use nonlocality.mermin_ghz3@0.4; mermin_ghz3(q);
exports mermin_ghz3#nonlocality#mermin#ghz#stabilizer#algorithm-pack-0.4

Simulator benchmarks

benchmark.stabilizer_rb100circuitv0.4100 qubits

stabilizer_rb100

Apply a deterministic 398-gate Clifford round trip on 100 qubits as a simulator regression workload, not a hardware RB fidelity estimate.

use benchmark.stabilizer_rb100@0.4; stabilizer_rb100(q);
exports stabilizer_rb100#benchmark#clifford#round-trip#stabilizer#100-qubit#algorithm-pack-0.4

Chemistry observables

chemistry.h2_minimalobservablev0.12 qubits

H2Minimal

Minimal two-qubit H2-style Hamiltonian for VQE and expectation demos.

use chemistry.h2_minimal; expect H2Minimal
exports H2Minimal#chemistry#hamiltonian#vqe#expectation
chemistry.heisenberg2observablev0.12 qubits

Heisenberg2

Two-spin isotropic Heisenberg Hamiltonian with XX, YY, and ZZ interactions.

use chemistry.heisenberg2; expect Heisenberg2
exports Heisenberg2#chemistry#spin#hamiltonian#vqe
chemistry.ising_trotter2circuitv0.22 qubits

ising_trotter2

One first-order two-qubit Ising Trotter layer with ZZ interaction and transverse-X mixing.

use chemistry.ising_trotter2@0.2; ising_trotter2(q, gamma, beta);
exports ising_trotter2#ising#trotter#hamiltonian-simulation#algorithm-pack-0.2

Optimization observables

optimization.maxcut2observablev0.12 qubits

MaxCut2

Two-node MaxCut cost Hamiltonian, (I - Z0 Z1) / 2, for QAOA lessons.

use optimization.maxcut2; expect MaxCut2
exports MaxCut2#optimization#maxcut#qaoa#hamiltonian

Machine-learning packages

ml.vqc_layercircuitv0.12 qubits

vqc_layer

Two-qubit hardware-efficient variational layer.

use ml.vqc_layer; vqc_layer(q, t1, t2);
exports vqc_layer#qml#variational#ansatz
ml.vqc_layer3circuitv0.13 qubits

vqc_layer3

Three-qubit hardware-efficient variational layer.

use ml.vqc_layer3; vqc_layer3(q, t1, t2, t3);
exports vqc_layer3#qml#variational#ansatz
ml.reupload_blockcircuitv0.11 qubits

reupload_block

Single-qubit data re-uploading block.

use ml.reupload_block; reupload_block(q, x, w);
exports reupload_block#qml#encoding#reupload
Standard library

Example registry

These examples come from the same registry used by the playground, so runnable and spec-preview samples stay clearly separated.

Hello Quantum

Readybasics

Create your first N/M register, entangle two qubits, and measure the result.

Classical functions (experimental)

Readybasics

Call typed functions and return a computed result. This example enables three experimental options.

Superposition

Readybasics

Use one Hadamard gate to create a 50/50 measurement distribution.

Bell State

Readybasics

Create the standard Bell pair with H plus CNOT.

Extended Gate Set

Readyhardware

Try universal phase gates, interaction rotations, iSWAP, and controlled-SWAP.

MPS Tensor Network (20 Qubits)

Readyhardware

Simulate a 20-qubit entangled GHZ state with Matrix Product States and inspect entanglement entropy.

Conditional Else

Readybasics

Use a measured Bit to choose between two correction branches.

Bounded Retry

Readyalgorithm

Use until ... max to retry a measurement-driven step without risking an infinite loop.

Public npm installation

Use N/M from JavaScript

Install the Core ES module API and TypeScript declarations in your Node.js project.

Requires Node.js 20 or newer. Release checks use Node.js 22.23.1.

npm package 0.2.1 targets N/M language 0.2.0. next selects the preview channel and can change; use @0.2.1 to reproduce this release. An untagged install selects latest. The VS Code extension has a separate distribution version.

npm install @nm-lang/core@next

To pin this release:

npm install @nm-lang/core@0.2.1

Save as bell.mjs and run node bell.mjs

import { createNMDefaultParseOptions, executeNMCode } from "@nm-lang/core";

const source = `module npm_bell;
fn main() {
  let q = qreg[2];
  H(q[0]);
  CNOT(q[0], q[1]);
  return q;
}`;

const result = executeNMCode(source, createNMDefaultParseOptions());
if (!result.success) throw new Error(result.error);
console.log(result);

Examples run on a local simulator. Installation does not establish physical QPU access or make every capability stable.

Personal, educational and commercial use is free. QuantumSoftware retains rights to its package code; modification and redistribution require separate permission. Your N/M programs and results remain yours. Read LICENSE.txt in the installed package.