libket 0.7.0

Runtime library for the Ket programming language
Documentation
// SPDX-FileCopyrightText: 2026 Evandro Chagas Ribeiro da Rosa <evandro@quantuloop.com>
//
// SPDX-License-Identifier: Apache-2.0

//! Libket: a quantum circuit compiler library.
//!
//! Libket translates high-level quantum gate sequences into hardware-native
//! instruction streams. It provides:
//!
//! - A rich intermediate representation ([`ir`]) with algebraic gate
//!   optimisations and multi-controlled gate decomposition.
//! - Pluggable execution backends ([`execution`]) for both live (mid-circuit
//!   feedback) and batch (deferred compilation) execution modes.
//! - A process abstraction ([`process`]) that drives the full compilation and
//!   execution pipeline.
//! - A structured, FFI-friendly error type ([`error::KetError`]).

use crate::{
    error::KetError,
    ir::{block::BasicBlock, gate::QuantumGate},
};

pub mod c_api;
mod decompose;
pub mod error;
pub mod execution;
pub mod ir;
mod mapping;
mod matrix;
pub mod process;

#[cfg(test)]
mod tests;

/// Return a block with a controlled gate.
///
/// # Errors
///
/// Propagates any [`KetError`] that occurs during the `control` operation.
pub fn controlled_gate(
    gate: QuantumGate,
    control: &[usize],
    target: usize,
) -> Result<BasicBlock, KetError> {
    let mut quantum_code = BasicBlock::new();
    quantum_code.append_gate(gate, target);
    quantum_code.control(control)
}

/// Return a block with a SWAP gate.
///
/// # Errors
///
/// Propagates any [`KetError`] that occurs during the `controlled_gate` operation.
pub fn swap_gate(a: usize, b: usize) -> Result<BasicBlock, KetError> {
    let mut quantum_code = BasicBlock::new();
    quantum_code.append_block(controlled_gate(QuantumGate::PauliX, &[a], b)?, None);
    quantum_code.append_block(controlled_gate(QuantumGate::PauliX, &[b], a)?, None);
    quantum_code.append_block(controlled_gate(QuantumGate::PauliX, &[a], b)?, None);
    Ok(quantum_code)
}

/// Return a block with the compute-action-uncompute.
///
/// # Errors
///
/// Propagates any [`KetError`] that occurs during `compute` or `action` block generation.
pub fn compute_action_uncompute_gate<Fc, Fa>(
    mut compute: Fc,
    mut action: Fa,
) -> Result<BasicBlock, KetError>
where
    Fc: FnMut(BasicBlock) -> Result<BasicBlock, KetError>,
    Fa: FnMut(BasicBlock) -> Result<BasicBlock, KetError>,
{
    let mut quantum_code = BasicBlock::new();

    let compute = compute(BasicBlock::new())?;
    let uncompute = compute.inverse();

    let action = action(BasicBlock::new())?;

    quantum_code.append_block(compute, None);
    quantum_code.append_block(action, None);
    quantum_code.append_block(uncompute, None);

    Ok(quantum_code)
}