hugr_core/builder.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
//! Utilities for building valid HUGRs.
//!
//! This module includes various tools for building HUGRs.
//!
//! Depending on the type of HUGR you want to build, you may want to use one of
//! the following builders:
//!
//! - [ModuleBuilder]: For building a module with function declarations and
//! definitions.
//! - [DFGBuilder]: For building a dataflow graph.
//! - [FunctionBuilder]: A `DFGBuilder` specialised in defining functions with a
//! dataflow graph.
//! - [CFGBuilder]: For building a control flow graph.
//! - [ConditionalBuilder]: For building a conditional node.
//! - [TailLoopBuilder]: For building a tail-loop node.
//!
//! Additionally, the [CircuitBuilder] provides an alternative to the
//! [DFGBuilder] when working with circuits, where some inputs of operations directly
//! correspond to some outputs and operations can be directly appended using
//! unit indices.
//!
//! # Example
//!
//! The following example shows how to build a simple HUGR module with two
//! dataflow functions, one built using the `DFGBuilder` and the other using the
//! `CircuitBuilder`.
//!
//! ```rust
//! # use hugr::Hugr;
//! # use hugr::builder::{BuildError, BuildHandle, Container, DFGBuilder, Dataflow, DataflowHugr, ModuleBuilder, DataflowSubContainer, HugrBuilder};
//! use hugr::extension::prelude::bool_t;
//! use hugr::std_extensions::logic::{self, LogicOp};
//! use hugr::types::Signature;
//!
//! # fn doctest() -> Result<(), BuildError> {
//! let hugr = {
//! let mut module_builder = ModuleBuilder::new();
//!
//! // Add a `main` function with signature `bool -> bool`.
//! //
//! // This block returns a handle to the built function.
//! let _dfg_handle = {
//! let mut dfg = module_builder.define_function(
//! "main",
//! Signature::new_endo(bool_t()).with_extension_delta(logic::EXTENSION_ID),
//! )?;
//!
//! // Get the wires from the function inputs.
//! let [w] = dfg.input_wires_arr();
//!
//! // Add an operation connected to the input wire, and get the new dangling wires.
//! let [w] = dfg.add_dataflow_op(LogicOp::Not, [w])?.outputs_arr();
//!
//! // Finish the function, connecting some wires to the output.
//! dfg.finish_with_outputs([w])
//! }?;
//!
//! // Add a similar function, using the circuit builder interface.
//! let _circuit_handle = {
//! let mut dfg = module_builder.define_function(
//! "circuit",
//! Signature::new_endo(vec![bool_t(), bool_t()])
//! .with_extension_delta(logic::EXTENSION_ID),
//! )?;
//! let mut circuit = dfg.as_circuit(dfg.input_wires());
//!
//! // Add multiple operations, indicating only the wire index.
//! circuit.append(LogicOp::Not, [0])?.append(LogicOp::Not, [1])?;
//!
//! // Finish the circuit, and return the dataflow graph after connecting its outputs.
//! let outputs = circuit.finish();
//! dfg.finish_with_outputs(outputs)
//! }?;
//!
//! // Finish building the HUGR, consuming the builder.
//! //
//! // Requires a registry with all the extensions used in the module.
//! module_builder.finish_hugr()
//! }?;
//!
//! // The built HUGR is always valid.
//! hugr.validate().unwrap_or_else(|e| {
//! panic!("HUGR validation failed: {e}");
//! });
//! # Ok(())
//! # }
//! # doctest().unwrap();
//! ```
use thiserror::Error;
use crate::extension::simple_op::OpLoadError;
use crate::extension::{SignatureError, TO_BE_INFERRED};
use crate::hugr::ValidationError;
use crate::ops::handle::{BasicBlockID, CfgID, ConditionalID, DfgID, FuncID, TailLoopID};
use crate::ops::{NamedOp, OpType};
use crate::types::Type;
use crate::types::{ConstTypeError, Signature, TypeRow};
use crate::{Node, Port, Wire};
pub mod handle;
pub use handle::BuildHandle;
mod build_traits;
pub use build_traits::{
Container, Dataflow, DataflowHugr, DataflowSubContainer, HugrBuilder, SubContainer,
};
mod dataflow;
pub use dataflow::{DFGBuilder, DFGWrapper, FunctionBuilder};
mod module;
pub use module::ModuleBuilder;
mod cfg;
pub use cfg::{BlockBuilder, CFGBuilder};
mod tail_loop;
pub use tail_loop::TailLoopBuilder;
mod conditional;
pub use conditional::{CaseBuilder, ConditionalBuilder};
mod circuit;
pub use circuit::{CircuitBuildError, CircuitBuilder};
/// Return a FunctionType with the same input and output types (specified)
/// whose extension delta, when used in a non-FuncDefn container, will be inferred.
pub fn endo_sig(types: impl Into<TypeRow>) -> Signature {
Signature::new_endo(types).with_extension_delta(TO_BE_INFERRED)
}
/// Return a FunctionType with the specified input and output types
/// whose extension delta, when used in a non-FuncDefn container, will be inferred.
pub fn inout_sig(inputs: impl Into<TypeRow>, outputs: impl Into<TypeRow>) -> Signature {
Signature::new(inputs, outputs).with_extension_delta(TO_BE_INFERRED)
}
#[derive(Debug, Clone, PartialEq, Error)]
#[non_exhaustive]
/// Error while building the HUGR.
pub enum BuildError {
/// The constructed HUGR is invalid.
#[error("The constructed HUGR is invalid: {0}.")]
InvalidHUGR(#[from] ValidationError),
/// SignatureError in trying to construct a node (differs from
/// [ValidationError::SignatureError] in that we could not construct a node to report about)
#[error(transparent)]
SignatureError(#[from] SignatureError),
/// Tried to add a malformed [Const]
///
/// [Const]: crate::ops::constant::Const
#[error("Constant failed typechecking: {0}")]
BadConstant(#[from] ConstTypeError),
/// CFG can only have one entry.
#[error("CFG entry node already built for CFG node: {0}.")]
EntryBuiltError(Node),
/// Node was expected to have a certain type but was found to not.
#[error("Node with index {node} does not have type {op_desc} as expected.")]
#[allow(missing_docs)]
UnexpectedType {
/// Index of node where error occurred.
node: Node,
/// Description of expected node.
op_desc: &'static str,
},
/// Error building Conditional node
#[error("Error building Conditional node: {0}.")]
ConditionalError(#[from] conditional::ConditionalBuildError),
/// Wire not found in Hugr
#[error("Wire not found in Hugr: {0}.")]
WireNotFound(Wire),
/// Error in CircuitBuilder
#[error("Error in CircuitBuilder: {0}.")]
CircuitError(#[from] circuit::CircuitBuildError),
/// Invalid wires when setting outputs
#[error("Found an error while setting the outputs of a {} container, {container_node}. {error}", .container_op.name())]
#[allow(missing_docs)]
OutputWiring {
container_op: OpType,
container_node: Node,
#[source]
error: BuilderWiringError,
},
/// Invalid input wires to a new operation
///
/// The internal error message already contains the node index.
#[error("Got an input wire while adding a {} to the circuit. {error}", .op.name())]
#[allow(missing_docs)]
OperationWiring {
op: OpType,
#[source]
error: BuilderWiringError,
},
#[error("Failed to load an extension op: {0}")]
#[allow(missing_docs)]
ExtensionOp(#[from] OpLoadError),
}
#[derive(Debug, Clone, PartialEq, Error)]
#[non_exhaustive]
/// Error raised when wiring up a node during the build process.
pub enum BuilderWiringError {
/// Tried to copy a linear type.
#[error("Cannot copy linear type {typ} from output {src_offset} of node {src}")]
#[allow(missing_docs)]
NoCopyLinear {
typ: Type,
src: Node,
src_offset: Port,
},
/// The ancestors of an inter-graph edge are not related.
#[error("Cannot connect an inter-graph edge between unrelated nodes. Tried connecting {src} ({src_offset}) with {dst} ({dst_offset}).")]
#[allow(missing_docs)]
NoRelationIntergraph {
src: Node,
src_offset: Port,
dst: Node,
dst_offset: Port,
},
/// Inter-Graph edges can only carry copyable data.
#[error("Inter-graph edges cannot carry non-copyable data {typ}. Tried connecting {src} ({src_offset}) with {dst} ({dst_offset}).")]
#[allow(missing_docs)]
NonCopyableIntergraph {
src: Node,
src_offset: Port,
dst: Node,
dst_offset: Port,
typ: Type,
},
}
#[cfg(test)]
pub(crate) mod test {
use rstest::fixture;
use crate::extension::prelude::{bool_t, usize_t};
use crate::hugr::{views::HugrView, HugrMut};
use crate::ops;
use crate::types::{PolyFuncType, Signature};
use crate::Hugr;
use super::handle::BuildHandle;
use super::{
BuildError, CFGBuilder, Container, DFGBuilder, Dataflow, DataflowHugr, FuncID,
FunctionBuilder, ModuleBuilder,
};
use super::{DataflowSubContainer, HugrBuilder};
/// Wire up inputs of a Dataflow container to the outputs.
pub(crate) fn n_identity<T: DataflowSubContainer>(
dataflow_builder: T,
) -> Result<T::ContainerHandle, BuildError> {
let w = dataflow_builder.input_wires();
dataflow_builder.finish_with_outputs(w)
}
pub(crate) fn build_main(
signature: PolyFuncType,
f: impl FnOnce(FunctionBuilder<&mut Hugr>) -> Result<BuildHandle<FuncID<true>>, BuildError>,
) -> Result<Hugr, BuildError> {
let mut module_builder = ModuleBuilder::new();
let f_builder = module_builder.define_function("main", signature)?;
f(f_builder)?;
Ok(module_builder.finish_hugr()?)
}
#[fixture]
pub(crate) fn simple_dfg_hugr() -> Hugr {
let dfg_builder = DFGBuilder::new(Signature::new(vec![bool_t()], vec![bool_t()])).unwrap();
let [i1] = dfg_builder.input_wires_arr();
dfg_builder.finish_hugr_with_outputs([i1]).unwrap()
}
#[fixture]
pub(crate) fn simple_funcdef_hugr() -> Hugr {
let fn_builder =
FunctionBuilder::new("test", Signature::new(vec![bool_t()], vec![bool_t()])).unwrap();
let [i1] = fn_builder.input_wires_arr();
fn_builder.finish_hugr_with_outputs([i1]).unwrap()
}
#[fixture]
pub(crate) fn simple_module_hugr() -> Hugr {
let mut builder = ModuleBuilder::new();
let sig = Signature::new(vec![bool_t()], vec![bool_t()]);
builder.declare("test", sig.into()).unwrap();
builder.finish_hugr().unwrap()
}
#[fixture]
pub(crate) fn simple_cfg_hugr() -> Hugr {
let mut cfg_builder =
CFGBuilder::new(Signature::new(vec![usize_t()], vec![usize_t()])).unwrap();
super::cfg::test::build_basic_cfg(&mut cfg_builder).unwrap();
cfg_builder.finish_hugr().unwrap()
}
/// A helper method which creates a DFG rooted hugr with Input and Output node
/// only (no wires), given a function type with extension delta.
// TODO consider taking two type rows and using TO_BE_INFERRED
pub(crate) fn closed_dfg_root_hugr(signature: Signature) -> Hugr {
let mut hugr = Hugr::new(ops::DFG {
signature: signature.clone(),
});
hugr.add_node_with_parent(
hugr.root(),
ops::Input {
types: signature.input,
},
);
hugr.add_node_with_parent(
hugr.root(),
ops::Output {
types: signature.output,
},
);
hugr
}
}