Skip to main content

ket/
lib.rs

1// SPDX-FileCopyrightText: 2026 Evandro Chagas Ribeiro da Rosa <evandro@quantuloop.com>
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! Libket: a quantum circuit compiler library.
6//!
7//! Libket translates high-level quantum gate sequences into hardware-native
8//! instruction streams. It provides:
9//!
10//! - A rich intermediate representation ([`ir`]) with algebraic gate
11//!   optimisations and multi-controlled gate decomposition.
12//! - Pluggable execution backends ([`execution`]) for both live (mid-circuit
13//!   feedback) and batch (deferred compilation) execution modes.
14//! - A process abstraction ([`process`]) that drives the full compilation and
15//!   execution pipeline.
16//! - A structured, FFI-friendly error type ([`error::KetError`]).
17
18use crate::{
19    error::KetError,
20    ir::{block::BasicBlock, gate::QuantumGate},
21};
22
23#[cfg(feature = "c_api")]
24pub mod c_api;
25mod decompose;
26pub mod error;
27pub mod execution;
28pub mod ir;
29mod mapping;
30mod matrix;
31pub mod process;
32
33#[cfg(test)]
34mod tests;
35
36/// Return a block with a controlled gate.
37///
38/// # Errors
39///
40/// Propagates any [`KetError`] that occurs during the `control` operation.
41pub fn controlled_gate(
42    gate: QuantumGate,
43    control: &[usize],
44    target: usize,
45) -> Result<BasicBlock, KetError> {
46    let mut quantum_code = BasicBlock::new();
47    quantum_code.append_gate(gate, target);
48    quantum_code.control(control)
49}
50
51/// Return a block with a SWAP gate.
52///
53/// # Errors
54///
55/// Propagates any [`KetError`] that occurs during the `controlled_gate` operation.
56pub fn swap_gate(a: usize, b: usize) -> Result<BasicBlock, KetError> {
57    let mut quantum_code = BasicBlock::new();
58    quantum_code.append_block(controlled_gate(QuantumGate::PauliX, &[a], b)?, None);
59    quantum_code.append_block(controlled_gate(QuantumGate::PauliX, &[b], a)?, None);
60    quantum_code.append_block(controlled_gate(QuantumGate::PauliX, &[a], b)?, None);
61    Ok(quantum_code)
62}
63
64/// Return a block with the compute-action-uncompute.
65///
66/// # Errors
67///
68/// Propagates any [`KetError`] that occurs during `compute` or `action` block generation.
69pub fn compute_action_uncompute_gate<Fc, Fa>(
70    mut compute: Fc,
71    mut action: Fa,
72) -> Result<BasicBlock, KetError>
73where
74    Fc: FnMut(BasicBlock) -> Result<BasicBlock, KetError>,
75    Fa: FnMut(BasicBlock) -> Result<BasicBlock, KetError>,
76{
77    let mut quantum_code = BasicBlock::new();
78
79    let compute = compute(BasicBlock::new())?;
80    let uncompute = compute.inverse();
81
82    let action = action(BasicBlock::new())?;
83
84    quantum_code.append_block(compute, None);
85    quantum_code.append_block(action, None);
86    quantum_code.append_block(uncompute, None);
87
88    Ok(quantum_code)
89}