diff --git a/hugr-cli/tests/validate.rs b/hugr-cli/tests/validate.rs index cd9a3cb79..baf2e1a3b 100644 --- a/hugr-cli/tests/validate.rs +++ b/hugr-cli/tests/validate.rs @@ -12,9 +12,8 @@ use hugr::builder::{DFGBuilder, DataflowSubContainer, ModuleBuilder}; use hugr::types::Type; use hugr::{ builder::{Container, Dataflow}, - extension::prelude::{BOOL_T, QB_T}, - std_extensions::arithmetic::float_types::FLOAT64_TYPE, - type_row, + extension::prelude::{bool_t, qb_t}, + std_extensions::arithmetic::float_types::float64_type, types::Signature, Hugr, }; @@ -41,7 +40,7 @@ const FLOAT_EXT_FILE: &str = concat!( /// A test package, containing a module-rooted HUGR. #[fixture] -fn test_package(#[default(BOOL_T)] id_type: Type) -> Package { +fn test_package(#[default(bool_t())] id_type: Type) -> Package { let mut module = ModuleBuilder::new(); let df = module .define_function("test", Signature::new_endo(id_type)) @@ -57,7 +56,7 @@ fn test_package(#[default(BOOL_T)] id_type: Type) -> Package { /// A DFG-rooted HUGR. #[fixture] -fn test_hugr(#[default(BOOL_T)] id_type: Type) -> Hugr { +fn test_hugr(#[default(bool_t())] id_type: Type) -> Hugr { let mut df = DFGBuilder::new(Signature::new_endo(id_type)).unwrap(); let [i] = df.input_wires_arr(); df.set_outputs([i]).unwrap(); @@ -120,7 +119,7 @@ fn test_mermaid(test_hugr_file: NamedTempFile, mut cmd: Command) { #[fixture] fn bad_hugr_string() -> String { - let df = DFGBuilder::new(Signature::new_endo(type_row![QB_T])).unwrap(); + let df = DFGBuilder::new(Signature::new_endo(vec![qb_t()])).unwrap(); let bad_hugr = df.hugr().clone(); serde_json::to_string(&bad_hugr).unwrap() @@ -178,7 +177,7 @@ fn test_no_std(test_hugr_string: String, mut val_cmd: Command) { } #[fixture] -fn float_hugr_string(#[with(FLOAT64_TYPE)] test_hugr: Hugr) -> String { +fn float_hugr_string(#[with(float64_type())] test_hugr: Hugr) -> String { serde_json::to_string(&test_hugr).unwrap() } @@ -205,7 +204,7 @@ fn test_float_extension(float_hugr_string: String, mut val_cmd: Command) { val_cmd.assert().success().stderr(contains(VALID_PRINT)); } #[fixture] -fn package_string(#[with(FLOAT64_TYPE)] test_package: Package) -> String { +fn package_string(#[with(float64_type())] test_package: Package) -> String { serde_json::to_string(&test_package).unwrap() } diff --git a/hugr-core/src/builder.rs b/hugr-core/src/builder.rs index 8bde38cc6..5f19cc4c5 100644 --- a/hugr-core/src/builder.rs +++ b/hugr-core/src/builder.rs @@ -28,7 +28,7 @@ //! ```rust //! # use hugr::Hugr; //! # use hugr::builder::{BuildError, BuildHandle, Container, DFGBuilder, Dataflow, DataflowHugr, ModuleBuilder, DataflowSubContainer, HugrBuilder}; -//! use hugr::extension::prelude::BOOL_T; +//! use hugr::extension::prelude::bool_t; //! use hugr::std_extensions::logic::{EXTENSION_ID, LOGIC_REG, LogicOp}; //! use hugr::types::Signature; //! @@ -42,7 +42,7 @@ //! let _dfg_handle = { //! let mut dfg = module_builder.define_function( //! "main", -//! Signature::new_endo(BOOL_T).with_extension_delta(EXTENSION_ID), +//! Signature::new_endo(bool_t()).with_extension_delta(EXTENSION_ID), //! )?; //! //! // Get the wires from the function inputs. @@ -59,7 +59,7 @@ //! let _circuit_handle = { //! let mut dfg = module_builder.define_function( //! "circuit", -//! Signature::new_endo(vec![BOOL_T, BOOL_T]) +//! Signature::new_endo(vec![bool_t(), bool_t()]) //! .with_extension_delta(EXTENSION_ID), //! )?; //! let mut circuit = dfg.as_circuit(dfg.input_wires()); @@ -238,11 +238,12 @@ pub enum BuilderWiringError { 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::std_extensions::arithmetic::float_ops::FLOAT_OPS_REGISTRY; - use crate::types::{PolyFuncType, Signature, Type}; - use crate::{type_row, Hugr}; + use crate::types::{PolyFuncType, Signature}; + use crate::Hugr; use super::handle::BuildHandle; use super::{ @@ -251,10 +252,6 @@ pub(crate) mod test { }; use super::{DataflowSubContainer, HugrBuilder}; - pub(super) const NAT: Type = crate::extension::prelude::USIZE_T; - pub(super) const BIT: Type = crate::extension::prelude::BOOL_T; - pub(super) const QB: Type = crate::extension::prelude::QB_T; - /// Wire up inputs of a Dataflow container to the outputs. pub(crate) fn n_identity( dataflow_builder: T, @@ -277,7 +274,7 @@ pub(crate) mod test { #[fixture] pub(crate) fn simple_dfg_hugr() -> Hugr { - let dfg_builder = DFGBuilder::new(Signature::new(type_row![BIT], type_row![BIT])).unwrap(); + let dfg_builder = DFGBuilder::new(Signature::new(vec![bool_t()], vec![bool_t()])).unwrap(); let [i1] = dfg_builder.input_wires_arr(); dfg_builder.finish_prelude_hugr_with_outputs([i1]).unwrap() } @@ -285,7 +282,7 @@ pub(crate) mod test { #[fixture] pub(crate) fn simple_funcdef_hugr() -> Hugr { let fn_builder = - FunctionBuilder::new("test", Signature::new(type_row![BIT], type_row![BIT])).unwrap(); + FunctionBuilder::new("test", Signature::new(vec![bool_t()], vec![bool_t()])).unwrap(); let [i1] = fn_builder.input_wires_arr(); fn_builder.finish_prelude_hugr_with_outputs([i1]).unwrap() } @@ -293,7 +290,7 @@ pub(crate) mod test { #[fixture] pub(crate) fn simple_module_hugr() -> Hugr { let mut builder = ModuleBuilder::new(); - let sig = Signature::new(type_row![BIT], type_row![BIT]); + let sig = Signature::new(vec![bool_t()], vec![bool_t()]); builder.declare("test", sig.into()).unwrap(); builder.finish_prelude_hugr().unwrap() } @@ -301,7 +298,7 @@ pub(crate) mod test { #[fixture] pub(crate) fn simple_cfg_hugr() -> Hugr { let mut cfg_builder = - CFGBuilder::new(Signature::new(type_row![NAT], type_row![NAT])).unwrap(); + CFGBuilder::new(Signature::new(vec![usize_t()], vec![usize_t()])).unwrap(); super::cfg::test::build_basic_cfg(&mut cfg_builder).unwrap(); cfg_builder.finish_prelude_hugr().unwrap() } diff --git a/hugr-core/src/builder/cfg.rs b/hugr-core/src/builder/cfg.rs index bcb6aff3b..e5562b95c 100644 --- a/hugr-core/src/builder/cfg.rs +++ b/hugr-core/src/builder/cfg.rs @@ -51,21 +51,20 @@ use crate::{hugr::HugrMut, type_row, Hugr}; /// ops, type_row, /// types::{Signature, SumType, Type}, /// Hugr, +/// extension::prelude::usize_t, /// }; /// -/// const NAT: Type = prelude::USIZE_T; -/// /// fn make_cfg() -> Result { -/// let mut cfg_builder = CFGBuilder::new(Signature::new_endo(NAT))?; +/// let mut cfg_builder = CFGBuilder::new(Signature::new_endo(usize_t()))?; /// /// // Outputs from basic blocks must be packed in a sum which corresponds to /// // which successor to pick. We'll either choose the first branch and pass -/// // it a NAT, or the second branch and pass it nothing. -/// let sum_variants = vec![type_row![NAT], type_row![]]; +/// // it a usize, or the second branch and pass it nothing. +/// let sum_variants = vec![vec![usize_t()].into(), type_row![]]; /// /// // The second argument says what types will be passed through to every /// // successor, in addition to the appropriate `sum_variants` type. -/// let mut entry_b = cfg_builder.entry_builder(sum_variants.clone(), type_row![NAT])?; +/// let mut entry_b = cfg_builder.entry_builder(sum_variants.clone(), vec![usize_t()].into())?; /// /// let [inw] = entry_b.input_wires_arr(); /// let entry = { @@ -81,10 +80,10 @@ use crate::{hugr::HugrMut, type_row, Hugr}; /// }; /// /// // This block will be the first successor of the entry node. It takes two -/// // `NAT` arguments: one from the `sum_variants` type, and another from the +/// // `usize` arguments: one from the `sum_variants` type, and another from the /// // entry node's `other_outputs`. /// let mut successor_builder = cfg_builder.simple_block_builder( -/// inout_sig(type_row![NAT, NAT], NAT), +/// inout_sig(vec![usize_t(), usize_t()], usize_t()), /// 1, // only one successor to this block /// )?; /// let successor_a = { @@ -98,7 +97,7 @@ use crate::{hugr::HugrMut, type_row, Hugr}; /// }; /// /// // The only argument to this block is the entry node's `other_outputs`. -/// let mut successor_builder = cfg_builder.simple_block_builder(endo_sig(NAT), 1)?; +/// let mut successor_builder = cfg_builder.simple_block_builder(endo_sig(usize_t()), 1)?; /// let successor_b = { /// let sum_unary = successor_builder.add_load_value(ops::Value::unary_unit_sum()); /// let [in_wire] = successor_builder.input_wires_arr(); @@ -464,9 +463,10 @@ impl BlockBuilder { pub(crate) mod test { use crate::builder::{DataflowSubContainer, ModuleBuilder}; + use crate::extension::prelude::usize_t; use crate::hugr::validate::InterGraphEdgeError; use crate::hugr::ValidationError; - use crate::{builder::test::NAT, type_row}; + use crate::type_row; use cool_asserts::assert_matches; use super::*; @@ -475,13 +475,13 @@ pub(crate) mod test { let build_result = { let mut module_builder = ModuleBuilder::new(); let mut func_builder = module_builder - .define_function("main", Signature::new(vec![NAT], type_row![NAT]))?; + .define_function("main", Signature::new(vec![usize_t()], vec![usize_t()]))?; let _f_id = { let [int] = func_builder.input_wires_arr(); let cfg_id = { let mut cfg_builder = - func_builder.cfg_builder(vec![(NAT, int)], type_row![NAT])?; + func_builder.cfg_builder(vec![(usize_t(), int)], vec![usize_t()].into())?; build_basic_cfg(&mut cfg_builder)?; cfg_builder.finish_sub_container()? @@ -498,7 +498,7 @@ pub(crate) mod test { } #[test] fn basic_cfg_hugr() -> Result<(), BuildError> { - let mut cfg_builder = CFGBuilder::new(Signature::new(type_row![NAT], type_row![NAT]))?; + let mut cfg_builder = CFGBuilder::new(Signature::new(vec![usize_t()], vec![usize_t()]))?; build_basic_cfg(&mut cfg_builder)?; assert_matches!(cfg_builder.finish_prelude_hugr(), Ok(_)); @@ -508,7 +508,8 @@ pub(crate) mod test { pub(crate) fn build_basic_cfg + AsRef>( cfg_builder: &mut CFGBuilder, ) -> Result<(), BuildError> { - let sum2_variants = vec![type_row![NAT], type_row![NAT]]; + let usize_row: TypeRow = vec![usize_t()].into(); + let sum2_variants = vec![usize_row.clone(), usize_row]; let mut entry_b = cfg_builder.entry_builder_exts( sum2_variants.clone(), type_row![], @@ -520,8 +521,8 @@ pub(crate) mod test { let sum = entry_b.make_sum(1, sum2_variants, [inw])?; entry_b.finish_with_outputs(sum, [])? }; - let mut middle_b = - cfg_builder.simple_block_builder(Signature::new(type_row![NAT], type_row![NAT]), 1)?; + let mut middle_b = cfg_builder + .simple_block_builder(Signature::new(vec![usize_t()], vec![usize_t()]), 1)?; let middle = { let c = middle_b.add_load_const(ops::Value::unary_unit_sum()); let [inw] = middle_b.input_wires_arr(); @@ -535,7 +536,7 @@ pub(crate) mod test { } #[test] fn test_dom_edge() -> Result<(), BuildError> { - let mut cfg_builder = CFGBuilder::new(Signature::new(type_row![NAT], type_row![NAT]))?; + let mut cfg_builder = CFGBuilder::new(Signature::new(vec![usize_t()], vec![usize_t()]))?; let sum_tuple_const = cfg_builder.add_constant(ops::Value::unary_unit_sum()); let sum_variants = vec![type_row![]]; @@ -551,7 +552,7 @@ pub(crate) mod test { entry_b.finish_with_outputs(sum, [])? }; let mut middle_b = - cfg_builder.simple_block_builder(Signature::new(type_row![], type_row![NAT]), 1)?; + cfg_builder.simple_block_builder(Signature::new(type_row![], vec![usize_t()]), 1)?; let middle = { let c = middle_b.load_const(&sum_tuple_const); middle_b.finish_with_outputs(c, [inw])? @@ -566,18 +567,19 @@ pub(crate) mod test { #[test] fn test_non_dom_edge() -> Result<(), BuildError> { - let mut cfg_builder = CFGBuilder::new(Signature::new(type_row![NAT], type_row![NAT]))?; + let mut cfg_builder = CFGBuilder::new(Signature::new(vec![usize_t()], vec![usize_t()]))?; let sum_tuple_const = cfg_builder.add_constant(ops::Value::unary_unit_sum()); let sum_variants = vec![type_row![]]; - let mut middle_b = - cfg_builder.simple_block_builder(Signature::new(type_row![NAT], type_row![NAT]), 1)?; + let mut middle_b = cfg_builder + .simple_block_builder(Signature::new(vec![usize_t()], vec![usize_t()]), 1)?; let [inw] = middle_b.input_wires_arr(); let middle = { let c = middle_b.load_const(&sum_tuple_const); middle_b.finish_with_outputs(c, [inw])? }; - let mut entry_b = cfg_builder.entry_builder(sum_variants.clone(), type_row![NAT])?; + let mut entry_b = + cfg_builder.entry_builder(sum_variants.clone(), vec![usize_t()].into())?; let entry = { let sum = entry_b.load_const(&sum_tuple_const); // entry block uses wire from middle block even though middle block diff --git a/hugr-core/src/builder/circuit.rs b/hugr-core/src/builder/circuit.rs index 43c106209..edf9a9049 100644 --- a/hugr-core/src/builder/circuit.rs +++ b/hugr-core/src/builder/circuit.rs @@ -243,6 +243,7 @@ mod test { use super::*; use cool_asserts::assert_matches; + use crate::extension::prelude::{qb_t, usize_t}; use crate::extension::{ExtensionId, ExtensionSet, PRELUDE_REGISTRY}; use crate::std_extensions::arithmetic::float_types::{self, ConstF64}; use crate::utils::test_quantum_extension::{ @@ -250,19 +251,15 @@ mod test { }; use crate::Extension; use crate::{ - builder::{ - test::{build_main, NAT, QB}, - DataflowSubContainer, - }, - extension::prelude::BOOL_T, - type_row, + builder::{test::build_main, DataflowSubContainer}, + extension::prelude::bool_t, types::Signature, }; #[test] fn simple_linear() { let build_res = build_main( - Signature::new(type_row![QB, QB], type_row![QB, QB]) + Signature::new(vec![qb_t(), qb_t()], vec![qb_t(), qb_t()]) .with_extension_delta(test_quantum_extension::EXTENSION_ID) .with_extension_delta(float_types::EXTENSION_ID) .into(), @@ -302,7 +299,7 @@ mod test { ext.add_op( "MyOp".into(), "".to_string(), - Signature::new(vec![QB, NAT], vec![QB]), + Signature::new(vec![qb_t(), usize_t()], vec![qb_t()]), extension_ref, ) .unwrap(); @@ -312,12 +309,15 @@ mod test { .unwrap(); let build_res = build_main( - Signature::new(type_row![QB, QB, NAT], type_row![QB, QB, BOOL_T]) - .with_extension_delta(ExtensionSet::from_iter([ - test_quantum_extension::EXTENSION_ID, - my_ext_name, - ])) - .into(), + Signature::new( + vec![qb_t(), qb_t(), usize_t()], + vec![qb_t(), qb_t(), bool_t()], + ) + .with_extension_delta(ExtensionSet::from_iter([ + test_quantum_extension::EXTENSION_ID, + my_ext_name, + ])) + .into(), |mut f_build| { let [q0, q1, angle]: [Wire; 3] = f_build.input_wires_arr(); @@ -342,7 +342,7 @@ mod test { #[test] fn ancillae() { let build_res = build_main( - Signature::new_endo(QB) + Signature::new_endo(qb_t()) .with_extension_delta(test_quantum_extension::EXTENSION_ID) .into(), |mut f_build| { @@ -380,7 +380,7 @@ mod test { #[test] fn circuit_builder_errors() { let _build_res = build_main( - Signature::new_endo(type_row![QB, QB]).into(), + Signature::new_endo(vec![qb_t(), qb_t()]).into(), |mut f_build| { let mut circ = f_build.as_circuit(f_build.input_wires()); let [q0, q1] = circ.tracked_units_arr(); diff --git a/hugr-core/src/builder/conditional.rs b/hugr-core/src/builder/conditional.rs index 685d2c889..4e8039992 100644 --- a/hugr-core/src/builder/conditional.rs +++ b/hugr-core/src/builder/conditional.rs @@ -214,11 +214,9 @@ mod test { use crate::builder::{DataflowSubContainer, ModuleBuilder}; + use crate::extension::prelude::usize_t; use crate::{ - builder::{ - test::{n_identity, NAT}, - Dataflow, - }, + builder::{test::n_identity, Dataflow}, ops::Value, type_row, }; @@ -229,8 +227,8 @@ mod test { fn basic_conditional() -> Result<(), BuildError> { let mut conditional_b = ConditionalBuilder::new_exts( [type_row![], type_row![]], - type_row![NAT], - type_row![NAT], + vec![usize_t()], + vec![usize_t()], ExtensionSet::new(), )?; @@ -244,14 +242,14 @@ mod test { let build_result: Result = { let mut module_builder = ModuleBuilder::new(); let mut fbuild = module_builder - .define_function("main", Signature::new(type_row![NAT], type_row![NAT]))?; + .define_function("main", Signature::new(vec![usize_t()], vec![usize_t()]))?; let tru_const = fbuild.add_constant(Value::true_val()); let _fdef = { let const_wire = fbuild.load_const(&tru_const); let [int] = fbuild.input_wires_arr(); let conditional_id = { - let other_inputs = vec![(NAT, int)]; - let outputs = vec![NAT].into(); + let other_inputs = vec![(usize_t(), int)]; + let outputs = vec![usize_t()].into(); let mut conditional_b = fbuild.conditional_builder( ([type_row![], type_row![]], const_wire), other_inputs, diff --git a/hugr-core/src/builder/dataflow.rs b/hugr-core/src/builder/dataflow.rs index 04ec38b4b..af2df0ecf 100644 --- a/hugr-core/src/builder/dataflow.rs +++ b/hugr-core/src/builder/dataflow.rs @@ -315,8 +315,8 @@ pub(crate) mod test { use crate::builder::{ endo_sig, inout_sig, BuilderWiringError, DataflowSubContainer, ModuleBuilder, }; + use crate::extension::prelude::{bool_t, qb_t, usize_t}; use crate::extension::prelude::{Lift, Noop}; - use crate::extension::prelude::{BOOL_T, USIZE_T}; use crate::extension::{ExtensionId, SignatureError, EMPTY_REG, PRELUDE_REGISTRY}; use crate::hugr::validate::InterGraphEdgeError; use crate::ops::{handle::NodeHandle, OpTag}; @@ -326,23 +326,20 @@ pub(crate) mod test { use crate::types::type_param::TypeParam; use crate::types::{EdgeKind, FuncValueType, RowVariable, Signature, Type, TypeBound, TypeRV}; use crate::utils::test_quantum_extension::h_gate; - use crate::{ - builder::test::{n_identity, BIT, NAT, QB}, - type_row, Wire, - }; + use crate::{builder::test::n_identity, type_row, Wire}; use super::super::test::simple_dfg_hugr; use super::*; #[test] fn nested_identity() -> Result<(), BuildError> { let build_result = { - let mut outer_builder = DFGBuilder::new(endo_sig(type_row![NAT, QB]))?; + let mut outer_builder = DFGBuilder::new(endo_sig(vec![usize_t(), qb_t()]))?; let [int, qb] = outer_builder.input_wires_arr(); let q_out = outer_builder.add_dataflow_op(h_gate(), vec![qb])?; - let inner_builder = outer_builder.dfg_builder_endo([(NAT, int)])?; + let inner_builder = outer_builder.dfg_builder_endo([(usize_t(), int)])?; let inner_id = n_identity(inner_builder)?; outer_builder @@ -360,7 +357,7 @@ pub(crate) mod test { F: FnOnce(&mut DFGBuilder) -> Result<(), BuildError>, { let build_result = { - let mut builder = DFGBuilder::new(inout_sig(BOOL_T, type_row![BOOL_T, BOOL_T]))?; + let mut builder = DFGBuilder::new(inout_sig(bool_t(), vec![bool_t(), bool_t()]))?; f(&mut builder)?; @@ -408,7 +405,7 @@ pub(crate) mod test { let mut module_builder = ModuleBuilder::new(); let f_build = module_builder - .define_function("main", Signature::new(type_row![QB], type_row![QB, QB]))?; + .define_function("main", Signature::new(vec![qb_t()], vec![qb_t(), qb_t()]))?; let [q1] = f_build.input_wires_arr(); f_build.finish_with_outputs([q1, q1])?; @@ -422,7 +419,7 @@ pub(crate) mod test { error: BuilderWiringError::NoCopyLinear { typ, .. }, .. }) - if typ == QB + if typ == qb_t() ); } @@ -431,19 +428,19 @@ pub(crate) mod test { let builder = || -> Result { let mut f_build = FunctionBuilder::new( "main", - Signature::new(type_row![BIT], type_row![BIT]).with_prelude(), + Signature::new(vec![bool_t()], vec![bool_t()]).with_prelude(), )?; let [i1] = f_build.input_wires_arr(); - let noop = f_build.add_dataflow_op(Noop(BIT), [i1])?; + let noop = f_build.add_dataflow_op(Noop(bool_t()), [i1])?; let i1 = noop.out_wire(0); let mut nested = f_build.dfg_builder( - Signature::new(type_row![], type_row![BIT]).with_prelude(), + Signature::new(type_row![], vec![bool_t()]).with_prelude(), [], )?; - let id = nested.add_dataflow_op(Noop(BIT), [i1])?; + let id = nested.add_dataflow_op(Noop(bool_t()), [i1])?; let nested = nested.finish_with_outputs([id.out_wire(0)])?; @@ -458,21 +455,21 @@ pub(crate) mod test { let builder = || -> Result<(Hugr, Node), BuildError> { let mut f_build = FunctionBuilder::new( "main", - Signature::new(type_row![BIT], type_row![BIT]).with_prelude(), + Signature::new(vec![bool_t()], vec![bool_t()]).with_prelude(), )?; let f_node = f_build.container_node(); let [i0] = f_build.input_wires_arr(); - let noop0 = f_build.add_dataflow_op(Noop(BIT), [i0])?; + let noop0 = f_build.add_dataflow_op(Noop(bool_t()), [i0])?; // Some some order edges f_build.set_order(&f_build.io()[0], &noop0.node()); f_build.set_order(&noop0.node(), &f_build.io()[1]); // Add a new input and output, and connect them with a noop in between - f_build.add_output(QB); - let i1 = f_build.add_input(QB); - let noop1 = f_build.add_dataflow_op(Noop(QB), [i1])?; + f_build.add_output(qb_t()); + let i1 = f_build.add_input(qb_t()); + let noop1 = f_build.add_dataflow_op(Noop(qb_t()), [i1])?; let hugr = f_build.finish_prelude_hugr_with_outputs([noop0.out_wire(0), noop1.out_wire(0)])?; @@ -482,21 +479,26 @@ pub(crate) mod test { let (hugr, f_node) = builder().unwrap_or_else(|e| panic!("{e}")); let func_sig = hugr.get_optype(f_node).inner_function_type().unwrap(); - assert_eq!(func_sig.io(), (&type_row![BIT, QB], &type_row![BIT, QB])); + assert_eq!( + func_sig.io(), + ( + &vec![bool_t(), qb_t()].into(), + &vec![bool_t(), qb_t()].into() + ) + ); } #[test] fn error_on_linear_inter_graph_edge() -> Result<(), BuildError> { - let mut f_build = - FunctionBuilder::new("main", Signature::new(type_row![QB], type_row![QB]))?; + let mut f_build = FunctionBuilder::new("main", Signature::new(vec![qb_t()], vec![qb_t()]))?; let [i1] = f_build.input_wires_arr(); - let noop = f_build.add_dataflow_op(Noop(QB), [i1])?; + let noop = f_build.add_dataflow_op(Noop(qb_t()), [i1])?; let i1 = noop.out_wire(0); - let mut nested = f_build.dfg_builder(Signature::new(type_row![], type_row![QB]), [])?; + let mut nested = f_build.dfg_builder(Signature::new(type_row![], vec![qb_t()]), [])?; - let id_res = nested.add_dataflow_op(Noop(QB), [i1]); + let id_res = nested.add_dataflow_op(Noop(qb_t()), [i1]); // The error would anyway be caught in validation when we finish the Hugr, // but the builder catches it earlier @@ -520,7 +522,7 @@ pub(crate) mod test { #[test] fn insert_hugr() -> Result<(), BuildError> { // Create a simple DFG - let mut dfg_builder = DFGBuilder::new(Signature::new(type_row![BIT], type_row![BIT]))?; + let mut dfg_builder = DFGBuilder::new(Signature::new(vec![bool_t()], vec![bool_t()]))?; let [i1] = dfg_builder.input_wires_arr(); dfg_builder.set_metadata("x", 42); let dfg_hugr = dfg_builder.finish_hugr_with_outputs([i1], &EMPTY_REG)?; @@ -530,7 +532,7 @@ pub(crate) mod test { let (dfg_node, f_node) = { let mut f_build = module_builder - .define_function("main", Signature::new(type_row![BIT], type_row![BIT]))?; + .define_function("main", Signature::new(vec![bool_t()], vec![bool_t()]))?; let [i1] = f_build.input_wires_arr(); let dfg = f_build.add_hugr_with_wires(dfg_hugr, [i1])?; @@ -555,18 +557,18 @@ pub(crate) mod test { let xb: ExtensionId = "B".try_into().unwrap(); let xc: ExtensionId = "C".try_into().unwrap(); - let mut parent = DFGBuilder::new(endo_sig(BIT))?; + let mut parent = DFGBuilder::new(endo_sig(bool_t()))?; let [w] = parent.input_wires_arr(); // A box which adds extensions A and B, via child Lift nodes - let mut add_ab = parent.dfg_builder(endo_sig(BIT), [w])?; + let mut add_ab = parent.dfg_builder(endo_sig(bool_t()), [w])?; let [w] = add_ab.input_wires_arr(); - let lift_a = add_ab.add_dataflow_op(Lift::new(type_row![BIT], xa.clone()), [w])?; + let lift_a = add_ab.add_dataflow_op(Lift::new(vec![bool_t()].into(), xa.clone()), [w])?; let [w] = lift_a.outputs_arr(); - let lift_b = add_ab.add_dataflow_op(Lift::new(type_row![BIT], xb), [w])?; + let lift_b = add_ab.add_dataflow_op(Lift::new(vec![bool_t()].into(), xb), [w])?; let [w] = lift_b.outputs_arr(); let add_ab = add_ab.finish_with_outputs([w])?; @@ -574,9 +576,9 @@ pub(crate) mod test { // Add another node (a sibling to add_ab) which adds extension C // via a child lift node - let mut add_c = parent.dfg_builder(endo_sig(BIT), [w])?; + let mut add_c = parent.dfg_builder(endo_sig(bool_t()), [w])?; let [w] = add_c.input_wires_arr(); - let lift_c = add_c.add_dataflow_op(Lift::new(type_row![BIT], xc), [w])?; + let lift_c = add_c.add_dataflow_op(Lift::new(vec![bool_t()].into(), xc), [w])?; let wires: Vec = lift_c.outputs().collect(); let add_c = add_c.finish_with_outputs(wires)?; @@ -647,7 +649,7 @@ pub(crate) mod test { PolyFuncType::new( [TypeParam::new_list(TypeBound::Copyable)], Signature::new( - Type::new_function(FuncValueType::new(USIZE_T, tv.clone())), + Type::new_function(FuncValueType::new(usize_t(), tv.clone())), vec![], ), ), @@ -656,7 +658,7 @@ pub(crate) mod test { // But cannot eval it... let ev = e.instantiate_extension_op( "eval", - [vec![USIZE_T.into()].into(), vec![tv.into()].into()], + [vec![usize_t().into()].into(), vec![tv.into()].into()], &PRELUDE_REGISTRY, ); assert_eq!( @@ -673,11 +675,11 @@ pub(crate) mod test { let (mut hugr, load_constant, call) = { let mut builder = ModuleBuilder::new(); let func = builder - .declare("func", Signature::new_endo(BOOL_T).into()) + .declare("func", Signature::new_endo(bool_t()).into()) .unwrap(); let (load_constant, call) = { let mut builder = builder - .define_function("main", Signature::new(Type::EMPTY_TYPEROW, BOOL_T)) + .define_function("main", Signature::new(Type::EMPTY_TYPEROW, bool_t())) .unwrap(); let load_constant = builder.add_load_value(Value::true_val()); let [r] = builder diff --git a/hugr-core/src/builder/module.rs b/hugr-core/src/builder/module.rs index d2f144e04..1df328d83 100644 --- a/hugr-core/src/builder/module.rs +++ b/hugr-core/src/builder/module.rs @@ -159,13 +159,10 @@ impl + AsRef> ModuleBuilder { mod test { use cool_asserts::assert_matches; + use crate::extension::prelude::usize_t; use crate::{ - builder::{ - test::{n_identity, NAT}, - Dataflow, DataflowSubContainer, - }, + builder::{test::n_identity, Dataflow, DataflowSubContainer}, extension::{EMPTY_REG, PRELUDE_REGISTRY}, - type_row, types::Signature, }; @@ -177,7 +174,7 @@ mod test { let f_id = module_builder.declare( "main", - Signature::new(type_row![NAT], type_row![NAT]).into(), + Signature::new(vec![usize_t()], vec![usize_t()]).into(), )?; let mut f_build = module_builder.define_declaration(&f_id)?; @@ -217,10 +214,14 @@ mod test { let build_result = { let mut module_builder = ModuleBuilder::new(); - let mut f_build = module_builder - .define_function("main", Signature::new(type_row![NAT], type_row![NAT, NAT]))?; - let local_build = f_build - .define_function("local", Signature::new(type_row![NAT], type_row![NAT, NAT]))?; + let mut f_build = module_builder.define_function( + "main", + Signature::new(vec![usize_t()], vec![usize_t(), usize_t()]), + )?; + let local_build = f_build.define_function( + "local", + Signature::new(vec![usize_t()], vec![usize_t(), usize_t()]), + )?; let [wire] = local_build.input_wires_arr(); let f_id = local_build.finish_with_outputs([wire, wire])?; diff --git a/hugr-core/src/builder/tail_loop.rs b/hugr-core/src/builder/tail_loop.rs index 29134ce03..b3051c72e 100644 --- a/hugr-core/src/builder/tail_loop.rs +++ b/hugr-core/src/builder/tail_loop.rs @@ -106,12 +106,10 @@ impl TailLoopBuilder { mod test { use cool_asserts::assert_matches; + use crate::extension::prelude::bool_t; use crate::{ - builder::{ - test::{BIT, NAT}, - DataflowSubContainer, HugrBuilder, ModuleBuilder, SubContainer, - }, - extension::prelude::{ConstUsize, Lift, PRELUDE_ID, USIZE_T}, + builder::{DataflowSubContainer, HugrBuilder, ModuleBuilder, SubContainer}, + extension::prelude::{usize_t, ConstUsize, Lift, PRELUDE_ID}, hugr::ValidationError, ops::Value, type_row, @@ -123,7 +121,7 @@ mod test { fn basic_loop() -> Result<(), BuildError> { let build_result: Result = { let mut loop_b = - TailLoopBuilder::new_exts(vec![], vec![BIT], vec![USIZE_T], PRELUDE_ID)?; + TailLoopBuilder::new_exts(vec![], vec![bool_t()], vec![usize_t()], PRELUDE_ID)?; let [i1] = loop_b.input_wires_arr(); let const_wire = loop_b.add_load_value(ConstUsize::new(1)); @@ -142,15 +140,21 @@ mod test { let mut module_builder = ModuleBuilder::new(); let mut fbuild = module_builder.define_function( "main", - Signature::new(type_row![BIT], type_row![NAT]).with_prelude(), + Signature::new(vec![bool_t()], vec![usize_t()]).with_prelude(), )?; let _fdef = { let [b1] = fbuild - .add_dataflow_op(Lift::new(type_row![BIT], PRELUDE_ID), fbuild.input_wires())? + .add_dataflow_op( + Lift::new(vec![bool_t()].into(), PRELUDE_ID), + fbuild.input_wires(), + )? .outputs_arr(); let loop_id = { - let mut loop_b = - fbuild.tail_loop_builder(vec![(BIT, b1)], vec![], type_row![NAT])?; + let mut loop_b = fbuild.tail_loop_builder( + vec![(bool_t(), b1)], + vec![], + vec![usize_t()].into(), + )?; let signature = loop_b.loop_signature()?.clone(); let const_val = Value::true_val(); let const_wire = loop_b.add_load_const(Value::true_val()); @@ -164,7 +168,7 @@ mod test { let output_row = loop_b.internal_output_row()?; let mut conditional_b = loop_b.conditional_builder( ([type_row![], type_row![]], const_wire), - vec![(BIT, b1)], + vec![(bool_t(), b1)], output_row, )?; diff --git a/hugr-core/src/export.rs b/hugr-core/src/export.rs index b390362a6..06be24fa9 100644 --- a/hugr-core/src/export.rs +++ b/hugr-core/src/export.rs @@ -926,9 +926,8 @@ mod test { use crate::{ builder::{Dataflow, DataflowSubContainer}, - extension::prelude::QB_T, + extension::prelude::qb_t, std_extensions::arithmetic::float_types, - type_row, types::Signature, utils::test_quantum_extension::{self, cx_gate, h_gate}, Hugr, @@ -937,7 +936,7 @@ mod test { #[fixture] fn test_simple_circuit() -> Hugr { crate::builder::test::build_main( - Signature::new_endo(type_row![QB_T, QB_T]) + Signature::new_endo(vec![qb_t(), qb_t()]) .with_extension_delta(test_quantum_extension::EXTENSION_ID) .with_extension_delta(float_types::EXTENSION_ID) .into(), diff --git a/hugr-core/src/extension.rs b/hugr-core/src/extension.rs index 6d30d635e..afd46b11a 100644 --- a/hugr-core/src/extension.rs +++ b/hugr-core/src/extension.rs @@ -155,6 +155,11 @@ impl ExtensionRegistry { self.0.iter() } + /// Returns an iterator over the extensions ids in the registry. + pub fn ids(&self) -> impl Iterator { + self.0.keys() + } + /// Delete an extension from the registry and return it if it was present. pub fn remove_extension(&mut self, name: &ExtensionId) -> Option> { self.0.remove(name) diff --git a/hugr-core/src/extension/op_def.rs b/hugr-core/src/extension/op_def.rs index 6f33cf3ef..d9a3900fa 100644 --- a/hugr-core/src/extension/op_def.rs +++ b/hugr-core/src/extension/op_def.rs @@ -535,7 +535,7 @@ pub(super) mod test { use super::SignatureFromArgs; use crate::builder::{endo_sig, DFGBuilder, Dataflow, DataflowHugr}; use crate::extension::op_def::{CustomValidator, LowerFunc, OpDef, SignatureFunc}; - use crate::extension::prelude::USIZE_T; + use crate::extension::prelude::usize_t; use crate::extension::{ExtensionRegistry, ExtensionSet, PRELUDE}; use crate::extension::{SignatureError, EMPTY_REG, PRELUDE_REGISTRY}; use crate::ops::OpName; @@ -662,10 +662,10 @@ pub(super) mod test { let e = reg.get(&EXT_ID).unwrap(); let list_usize = - Type::new_extension(list_def.instantiate(vec![TypeArg::Type { ty: USIZE_T }])?); + Type::new_extension(list_def.instantiate(vec![TypeArg::Type { ty: usize_t() }])?); let mut dfg = DFGBuilder::new(endo_sig(vec![list_usize]))?; let rev = dfg.add_dataflow_op( - e.instantiate_extension_op(&OP_NAME, vec![TypeArg::Type { ty: USIZE_T }], ®) + e.instantiate_extension_op(&OP_NAME, vec![TypeArg::Type { ty: usize_t() }], ®) .unwrap(), dfg.input_wires(), )?; @@ -710,13 +710,14 @@ pub(super) mod test { ext.add_op("MyOp".into(), "".to_string(), SigFun(), extension_ref)?; // Base case, no type variables: - let args = [TypeArg::BoundedNat { n: 3 }, USIZE_T.into()]; + let args = [TypeArg::BoundedNat { n: 3 }, usize_t().into()]; assert_eq!( def.compute_signature(&args, &PRELUDE_REGISTRY), - Ok( - Signature::new(vec![USIZE_T; 3], vec![Type::new_tuple(vec![USIZE_T; 3])]) - .with_extension_delta(EXT_ID) + Ok(Signature::new( + vec![usize_t(); 3], + vec![Type::new_tuple(vec![usize_t(); 3])] ) + .with_extension_delta(EXT_ID)) ); assert_eq!(def.validate_args(&args, &PRELUDE_REGISTRY, &[]), Ok(())); @@ -745,7 +746,7 @@ pub(super) mod test { // First arg must be concrete, not a variable let kind = TypeParam::bounded_nat(NonZeroU64::new(5).unwrap()); - let args = [TypeArg::new_var_use(0, kind.clone()), USIZE_T.into()]; + let args = [TypeArg::new_var_use(0, kind.clone()), usize_t().into()]; // We can't prevent this from getting into our compute_signature implementation: assert_eq!( def.compute_signature(&args, &PRELUDE_REGISTRY), @@ -806,12 +807,12 @@ pub(super) mod test { #[test] fn instantiate_extension_delta() -> Result<(), Box> { - use crate::extension::prelude::{BOOL_T, PRELUDE_REGISTRY}; + use crate::extension::prelude::{bool_t, PRELUDE_REGISTRY}; let _ext = Extension::try_new_test_arc(EXT_ID, |ext, extension_ref| { let params: Vec = vec![TypeParam::Extensions]; let db_set = ExtensionSet::type_var(0); - let fun_ty = Signature::new_endo(BOOL_T).with_extension_delta(db_set); + let fun_ty = Signature::new_endo(bool_t()).with_extension_delta(db_set); let def = ext.add_op( "SimpleOp".into(), @@ -822,7 +823,7 @@ pub(super) mod test { // Concrete extension set let es = ExtensionSet::singleton(&EXT_ID); - let exp_fun_ty = Signature::new_endo(BOOL_T).with_extension_delta(es.clone()); + let exp_fun_ty = Signature::new_endo(bool_t()).with_extension_delta(es.clone()); let args = [TypeArg::Extensions { es }]; def.validate_args(&args, &PRELUDE_REGISTRY, ¶ms) diff --git a/hugr-core/src/extension/op_def/serialize_signature_func.rs b/hugr-core/src/extension/op_def/serialize_signature_func.rs index 88c8c30de..6c189cc84 100644 --- a/hugr-core/src/extension/op_def/serialize_signature_func.rs +++ b/hugr-core/src/extension/op_def/serialize_signature_func.rs @@ -57,7 +57,7 @@ mod test { use super::*; use crate::{ extension::{ - prelude::USIZE_T, CustomSignatureFunc, CustomValidator, ExtensionRegistry, OpDef, + prelude::usize_t, CustomSignatureFunc, CustomValidator, ExtensionRegistry, OpDef, SignatureError, ValidateTypeArgs, }, types::{FuncValueType, Signature, TypeArg}, @@ -121,7 +121,7 @@ mod test { #[test] fn test_serial_sig_func() { // test round-trip - let sig: FuncValueType = Signature::new_endo(USIZE_T.clone()).into(); + let sig: FuncValueType = Signature::new_endo(usize_t().clone()).into(); let simple: SignatureFunc = sig.clone().into(); let ser: SerSignatureFunc = simple.into(); let expected_ser = SerSignatureFunc { diff --git a/hugr-core/src/extension/prelude.rs b/hugr-core/src/extension/prelude.rs index 691a9cfb6..8985e5002 100644 --- a/hugr-core/src/extension/prelude.rs +++ b/hugr-core/src/extension/prelude.rs @@ -1,6 +1,6 @@ //! Prelude extension - available in all contexts, defining common types, //! operations and constants. -use std::sync::Arc; +use std::sync::{Arc, Weak}; use itertools::Itertools; use lazy_static::lazy_static; @@ -40,8 +40,19 @@ pub const PRELUDE_ID: ExtensionId = ExtensionId::new_unchecked("prelude"); /// Extension version. pub const VERSION: semver::Version = semver::Version::new(0, 1, 0); lazy_static! { - static ref PRELUDE_DEF: Arc = { + /// Prelude extension, containing common types and operations. + pub static ref PRELUDE: Arc = { Extension::new_arc(PRELUDE_ID, VERSION, |prelude, extension_ref| { + + // Construct the list and error types using the passed extension + // reference. + // + // If we tried to use `string_type()` or `error_type()` directly it + // would try to access the `PRELUDE` lazy static recursively, + // causing a deadlock. + let string_type: Type = string_custom_type(extension_ref).into(); + let error_type: CustomType = error_custom_type(extension_ref); + prelude .add_type( TypeName::new_inline("usize"), @@ -62,7 +73,7 @@ lazy_static! { prelude.add_op( PRINT_OP_ID, "Print the string to standard output".to_string(), - Signature::new(type_row![STRING_TYPE], type_row![]), + Signature::new(vec![string_type], type_row![]), extension_ref, ) .unwrap(); @@ -74,7 +85,6 @@ lazy_static! { extension_ref, ) .unwrap(); - prelude .add_type( TypeName::new_inline("qubit"), @@ -93,7 +103,6 @@ lazy_static! { extension_ref, ) .unwrap(); - prelude .add_op( PANIC_OP_ID, @@ -101,7 +110,7 @@ lazy_static! { PolyFuncTypeRV::new( [TypeParam::new_list(TypeBound::Any), TypeParam::new_list(TypeBound::Any)], FuncValueType::new( - vec![TypeRV::new_extension(ERROR_CUSTOM_TYPE), TypeRV::new_row_var_use(0, TypeBound::Any)], + vec![TypeRV::new_extension(error_type), TypeRV::new_row_var_use(0, TypeBound::Any)], vec![TypeRV::new_row_var_use(1, TypeBound::Any)], ), ), @@ -116,30 +125,44 @@ lazy_static! { array::ArrayScanDef.add_to_extension(prelude, extension_ref).unwrap(); }) }; + /// An extension registry containing only the prelude pub static ref PRELUDE_REGISTRY: ExtensionRegistry = - ExtensionRegistry::try_new([PRELUDE_DEF.clone()]).unwrap(); - - /// Prelude extension - pub static ref PRELUDE: Arc = PRELUDE_REGISTRY.get(&PRELUDE_ID).unwrap().clone(); - + ExtensionRegistry::try_new([PRELUDE.clone()]).unwrap(); } -pub(crate) const USIZE_CUSTOM_T: CustomType = CustomType::new_simple( - TypeName::new_inline("usize"), - PRELUDE_ID, - TypeBound::Copyable, -); +pub(crate) fn usize_custom_t(extension_ref: &Weak) -> CustomType { + CustomType::new( + TypeName::new_inline("usize"), + vec![], + PRELUDE_ID, + TypeBound::Copyable, + extension_ref, + ) +} -pub(crate) const QB_CUSTOM_T: CustomType = - CustomType::new_simple(TypeName::new_inline("qubit"), PRELUDE_ID, TypeBound::Any); +pub(crate) fn qb_custom_t(extension_ref: &Weak) -> CustomType { + CustomType::new( + TypeName::new_inline("qubit"), + vec![], + PRELUDE_ID, + TypeBound::Any, + extension_ref, + ) +} /// Qubit type. -pub const QB_T: Type = Type::new_extension(QB_CUSTOM_T); +pub fn qb_t() -> Type { + qb_custom_t(&Arc::downgrade(&PRELUDE)).into() +} /// Unsigned size type. -pub const USIZE_T: Type = Type::new_extension(USIZE_CUSTOM_T); +pub fn usize_t() -> Type { + usize_custom_t(&Arc::downgrade(&PRELUDE)).into() +} /// Boolean type - Sum of two units. -pub const BOOL_T: Type = Type::new_unit_sum(2); +pub fn bool_t() -> Type { + Type::new_unit_sum(2) +} /// Name of the prelude panic operation. /// @@ -156,11 +179,23 @@ pub const PANIC_OP_ID: OpName = OpName::new_inline("panic"); pub const STRING_TYPE_NAME: TypeName = TypeName::new_inline("string"); /// Custom type for strings. -pub const STRING_CUSTOM_TYPE: CustomType = - CustomType::new_simple(STRING_TYPE_NAME, PRELUDE_ID, TypeBound::Copyable); +/// +/// Receives a reference to the prelude extensions as a parameter. +/// This avoids deadlocks when we are in the process of creating the prelude. +fn string_custom_type(extension_ref: &Weak) -> CustomType { + CustomType::new( + STRING_TYPE_NAME, + vec![], + PRELUDE_ID, + TypeBound::Copyable, + extension_ref, + ) +} /// String type. -pub const STRING_TYPE: Type = Type::new_extension(STRING_CUSTOM_TYPE); +pub fn string_type() -> Type { + string_custom_type(&Arc::downgrade(&PRELUDE)).into() +} #[derive(Debug, Clone, PartialEq, Hash, serde::Serialize, serde::Deserialize)] /// Structure for holding constant string values. @@ -193,7 +228,7 @@ impl CustomConst for ConstString { } fn get_type(&self) -> Type { - STRING_TYPE + string_type() } } @@ -201,17 +236,30 @@ impl CustomConst for ConstString { pub const PRINT_OP_ID: OpName = OpName::new_inline("print"); /// The custom type for Errors. -pub const ERROR_CUSTOM_TYPE: CustomType = - CustomType::new_simple(ERROR_TYPE_NAME, PRELUDE_ID, TypeBound::Copyable); +/// +/// Receives a reference to the prelude extensions as a parameter. +/// This avoids deadlocks when we are in the process of creating the prelude. +fn error_custom_type(extension_ref: &Weak) -> CustomType { + CustomType::new( + ERROR_TYPE_NAME, + vec![], + PRELUDE_ID, + TypeBound::Copyable, + extension_ref, + ) +} + /// Unspecified opaque error type. -pub const ERROR_TYPE: Type = Type::new_extension(ERROR_CUSTOM_TYPE); +pub fn error_type() -> Type { + error_custom_type(&Arc::downgrade(&PRELUDE)).into() +} /// The string name of the error type. pub const ERROR_TYPE_NAME: TypeName = TypeName::new_inline("error"); /// Return a Sum type with the second variant as the given type and the first an Error. pub fn sum_with_error(ty: impl Into) -> SumType { - either_type(ERROR_TYPE, ty) + either_type(error_type(), ty) } /// An optional type, i.e. a Sum type with the second variant as the given type and the first as an empty tuple. @@ -373,7 +421,7 @@ impl CustomConst for ConstUsize { } fn get_type(&self) -> Type { - USIZE_T + usize_t() } } @@ -418,7 +466,7 @@ impl CustomConst for ConstError { ExtensionSet::singleton(&PRELUDE_ID) } fn get_type(&self) -> Type { - ERROR_TYPE + error_type() } } @@ -508,7 +556,7 @@ impl ConstFold for TupleOpDef { } } impl MakeOpDef for TupleOpDef { - fn signature(&self) -> SignatureFunc { + fn init_signature(&self, _extension_ref: &Weak) -> SignatureFunc { let rv = TypeRV::new_row_var_use(0, TypeBound::Any); let tuple_type = TypeRV::new_tuple(vec![rv.clone()]); @@ -540,6 +588,10 @@ impl MakeOpDef for TupleOpDef { PRELUDE_ID.to_owned() } + fn extension_ref(&self) -> Weak { + Arc::downgrade(&PRELUDE) + } + fn post_opdef(&self, def: &mut OpDef) { def.set_constant_folder(*self); } @@ -690,7 +742,7 @@ impl std::str::FromStr for NoopDef { } } impl MakeOpDef for NoopDef { - fn signature(&self) -> SignatureFunc { + fn init_signature(&self, _extension_ref: &Weak) -> SignatureFunc { let tv = Type::new_var_use(0, TypeBound::Any); PolyFuncType::new([TypeBound::Any.into()], Signature::new_endo(tv)).into() } @@ -707,6 +759,10 @@ impl MakeOpDef for NoopDef { PRELUDE_ID.to_owned() } + fn extension_ref(&self) -> Weak { + Arc::downgrade(&PRELUDE) + } + fn post_opdef(&self, def: &mut OpDef) { def.set_constant_folder(*self); } @@ -796,7 +852,7 @@ impl std::str::FromStr for LiftDef { } impl MakeOpDef for LiftDef { - fn signature(&self) -> SignatureFunc { + fn init_signature(&self, _extension_ref: &Weak) -> SignatureFunc { PolyFuncTypeRV::new( vec![TypeParam::Extensions, TypeParam::new_list(TypeBound::Any)], FuncValueType::new_endo(TypeRV::new_row_var_use(1, TypeBound::Any)) @@ -816,6 +872,10 @@ impl MakeOpDef for LiftDef { fn extension(&self) -> ExtensionId { PRELUDE_ID.to_owned() } + + fn extension_ref(&self) -> Weak { + Arc::downgrade(&PRELUDE) + } } /// A node which adds a extension req to the types of the wires it is passed @@ -899,7 +959,7 @@ impl MakeRegisteredOp for Lift { mod test { use crate::builder::inout_sig; use crate::std_extensions::arithmetic::float_ops::FLOAT_OPS_REGISTRY; - use crate::std_extensions::arithmetic::float_types::{ConstF64, FLOAT64_TYPE}; + use crate::std_extensions::arithmetic::float_types::{float64_type, ConstF64}; use crate::{ builder::{endo_sig, DFGBuilder, Dataflow, DataflowHugr}, utils::test_quantum_extension::cx_gate, @@ -977,14 +1037,14 @@ mod test { /// Test building a HUGR involving a new_array operation. fn test_new_array() { let mut b = DFGBuilder::new(inout_sig( - vec![QB_T, QB_T], - array_type(TypeArg::BoundedNat { n: 2 }, QB_T), + vec![qb_t(), qb_t()], + array_type(TypeArg::BoundedNat { n: 2 }, qb_t()), )) .unwrap(); let [q1, q2] = b.input_wires_arr(); - let op = new_array_op(QB_T, 2); + let op = new_array_op(qb_t(), 2); let out = b.add_dataflow_op(op, [q1, q2]).unwrap(); @@ -993,9 +1053,9 @@ mod test { #[test] fn test_option() { - let typ: Type = option_type(BOOL_T).into(); + let typ: Type = option_type(bool_t()).into(); let const_val1 = const_some(Value::true_val()); - let const_val2 = const_none(BOOL_T); + let const_val2 = const_none(bool_t()); let mut b = DFGBuilder::new(inout_sig(type_row![], vec![typ.clone(), typ])).unwrap(); @@ -1007,9 +1067,9 @@ mod test { #[test] fn test_result() { - let typ: Type = either_type(BOOL_T, FLOAT64_TYPE).into(); - let const_bool = const_left(Value::true_val(), FLOAT64_TYPE); - let const_float = const_right(BOOL_T, ConstF64::new(0.5).into()); + let typ: Type = either_type(bool_t(), float64_type()).into(); + let const_bool = const_left(Value::true_val(), float64_type()); + let const_float = const_right(bool_t(), ConstF64::new(0.5).into()); let mut b = DFGBuilder::new(inout_sig(type_row![], vec![typ.clone(), typ])).unwrap(); @@ -1030,7 +1090,7 @@ mod test { .unwrap(); let ext_type = Type::new_extension(ext_def); - assert_eq!(ext_type, ERROR_TYPE); + assert_eq!(ext_type, error_type()); let error_val = ConstError::new(2, "my message"); @@ -1067,9 +1127,9 @@ mod test { /// test the panic operation with input and output wires fn test_panic_with_io() { let error_val = ConstError::new(42, "PANIC"); - const TYPE_ARG_Q: TypeArg = TypeArg::Type { ty: QB_T }; + let type_arg_q: TypeArg = TypeArg::Type { ty: qb_t() }; let type_arg_2q: TypeArg = TypeArg::Sequence { - elems: vec![TYPE_ARG_Q, TYPE_ARG_Q], + elems: vec![type_arg_q.clone(), type_arg_q], }; let panic_op = PRELUDE .instantiate_extension_op( @@ -1079,7 +1139,7 @@ mod test { ) .unwrap(); - let mut b = DFGBuilder::new(endo_sig(type_row![QB_T, QB_T])).unwrap(); + let mut b = DFGBuilder::new(endo_sig(vec![qb_t(), qb_t()])).unwrap(); let [q0, q1] = b.input_wires_arr(); let [q0, q1] = b .add_dataflow_op(cx_gate(), [q0, q1]) @@ -1101,8 +1161,8 @@ mod test { .unwrap() .instantiate([]) .unwrap(); - let string_type: Type = Type::new_extension(string_custom_type); - assert_eq!(string_type, STRING_TYPE); + let string_ty: Type = Type::new_extension(string_custom_type); + assert_eq!(string_ty, string_type()); let string_const: ConstString = ConstString::new("Lorem ipsum".into()); assert_eq!(string_const.name(), "ConstString(\"Lorem ipsum\")"); assert!(string_const.validate().is_ok()); @@ -1139,7 +1199,7 @@ mod test { ); assert!(subject.equal_consts(&ConstExternalSymbol::new("foo", Type::UNIT, false))); assert!(!subject.equal_consts(&ConstExternalSymbol::new("bar", Type::UNIT, false))); - assert!(!subject.equal_consts(&ConstExternalSymbol::new("foo", STRING_TYPE, false))); + assert!(!subject.equal_consts(&ConstExternalSymbol::new("foo", string_type(), false))); assert!(!subject.equal_consts(&ConstExternalSymbol::new("foo", Type::UNIT, true))); assert!(ConstExternalSymbol::new("", Type::UNIT, true) diff --git a/hugr-core/src/extension/prelude/array.rs b/hugr-core/src/extension/prelude/array.rs index c419a67c7..a26e2071b 100644 --- a/hugr-core/src/extension/prelude/array.rs +++ b/hugr-core/src/extension/prelude/array.rs @@ -1,14 +1,13 @@ use std::str::FromStr; -use std::sync::Weak; +use std::sync::{Arc, Weak}; use itertools::Itertools; use strum_macros::EnumIter; use strum_macros::EnumString; use strum_macros::IntoStaticStr; -use crate::extension::prelude::either_type; use crate::extension::prelude::option_type; -use crate::extension::prelude::USIZE_T; +use crate::extension::prelude::{either_type, usize_custom_t}; use crate::extension::simple_op::{ HasConcrete, HasDef, MakeExtensionOp, MakeOpDef, MakeRegisteredOp, OpLoadError, }; @@ -113,7 +112,11 @@ impl ArrayOpDef { } /// To avoid recursion when defining the extension, take the type definition as an argument. - fn signature_from_def(&self, array_def: &TypeDef) -> SignatureFunc { + fn signature_from_def( + &self, + array_def: &TypeDef, + extension_ref: &Weak, + ) -> SignatureFunc { use ArrayOpDef::*; if let new_array | pop_left | pop_right = self { // implements SignatureFromArgs @@ -125,6 +128,12 @@ impl ArrayOpDef { let array_ty = instantiate(array_def, size_var.clone(), elem_ty_var.clone()); let standard_params = vec![TypeParam::max_nat(), TypeBound::Any.into()]; + // Construct the usize type using the passed extension reference. + // + // If we tried to use `usize_t()` directly it would try to access + // the `PRELUDE` lazy static recursively, causing a deadlock. + let usize_t: Type = usize_custom_t(extension_ref).into(); + match self { repeat => { let func = @@ -141,7 +150,7 @@ impl ArrayOpDef { let option_type: Type = option_type(copy_elem_ty).into(); PolyFuncTypeRV::new( params, - FuncValueType::new(vec![copy_array_ty, USIZE_T], option_type), + FuncValueType::new(vec![copy_array_ty, usize_t], option_type), ) } set => { @@ -150,7 +159,7 @@ impl ArrayOpDef { PolyFuncTypeRV::new( standard_params, FuncValueType::new( - vec![array_ty.clone(), USIZE_T, elem_ty_var], + vec![array_ty.clone(), usize_t, elem_ty_var], result_type, ), ) @@ -159,7 +168,7 @@ impl ArrayOpDef { let result_type: Type = either_type(array_ty.clone(), array_ty.clone()).into(); PolyFuncTypeRV::new( standard_params, - FuncValueType::new(vec![array_ty, USIZE_T, USIZE_T], result_type), + FuncValueType::new(vec![array_ty, usize_t.clone(), usize_t], result_type), ) } discard_empty => PolyFuncTypeRV::new( @@ -184,8 +193,12 @@ impl MakeOpDef for ArrayOpDef { crate::extension::simple_op::try_from_name(op_def.name(), op_def.extension_id()) } - fn signature(&self) -> SignatureFunc { - self.signature_from_def(array_type_def()) + fn init_signature(&self, extension_ref: &Weak) -> SignatureFunc { + self.signature_from_def(array_type_def(), extension_ref) + } + + fn extension_ref(&self) -> Weak { + Arc::downgrade(&PRELUDE) } fn extension(&self) -> ExtensionId { @@ -219,7 +232,8 @@ impl MakeOpDef for ArrayOpDef { extension: &mut Extension, extension_ref: &Weak, ) -> Result<(), crate::extension::ExtensionBuildError> { - let sig = self.signature_from_def(extension.get_type(ARRAY_TYPE_NAME).unwrap()); + let sig = + self.signature_from_def(extension.get_type(ARRAY_TYPE_NAME).unwrap(), extension_ref); let def = extension.add_op(self.name(), self.description(), sig, extension_ref)?; self.post_opdef(def); @@ -359,7 +373,8 @@ impl FromStr for ArrayScanDef { } impl ArrayScanDef { - /// To avoid recursion when defining the extension, take the type definition as an argument. + /// To avoid recursion when defining the extension, take the type definition + /// and a reference to the extension as an argument. fn signature_from_def(&self, array_def: &TypeDef) -> SignatureFunc { // array, (T1, *A -> T2, *A), -> array, *A let params = vec![ @@ -399,10 +414,14 @@ impl MakeOpDef for ArrayScanDef { crate::extension::simple_op::try_from_name(op_def.name(), op_def.extension_id()) } - fn signature(&self) -> SignatureFunc { + fn init_signature(&self, _extension_ref: &Weak) -> SignatureFunc { self.signature_from_def(array_type_def()) } + fn extension_ref(&self) -> Weak { + Arc::downgrade(&PRELUDE) + } + fn extension(&self) -> ExtensionId { PRELUDE_ID } @@ -524,9 +543,10 @@ impl HasConcrete for ArrayScanDef { mod tests { use strum::IntoEnumIterator; + use crate::extension::prelude::usize_t; use crate::{ builder::{inout_sig, DFGBuilder, Dataflow, DataflowHugr}, - extension::prelude::{BOOL_T, QB_T}, + extension::prelude::{bool_t, qb_t}, ops::{OpTrait, OpType}, types::Signature, }; @@ -536,7 +556,11 @@ mod tests { #[test] fn test_array_ops() { for def in ArrayOpDef::iter() { - let ty = if def == ArrayOpDef::get { BOOL_T } else { QB_T }; + let ty = if def == ArrayOpDef::get { + bool_t() + } else { + qb_t() + }; let size = if def == ArrayOpDef::discard_empty { 0 } else { @@ -553,14 +577,14 @@ mod tests { /// Test building a HUGR involving a new_array operation. fn test_new_array() { let mut b = DFGBuilder::new(inout_sig( - vec![QB_T, QB_T], - array_type(TypeArg::BoundedNat { n: 2 }, QB_T), + vec![qb_t(), qb_t()], + array_type(TypeArg::BoundedNat { n: 2 }, qb_t()), )) .unwrap(); let [q1, q2] = b.input_wires_arr(); - let op = new_array_op(QB_T, 2); + let op = new_array_op(qb_t(), 2); let out = b.add_dataflow_op(op, [q1, q2]).unwrap(); @@ -570,7 +594,7 @@ mod tests { #[test] fn test_get() { let size = 2; - let element_ty = BOOL_T; + let element_ty = bool_t(); let op = ArrayOpDef::get.to_concrete(element_ty.clone(), size); let optype: OpType = op.into(); @@ -580,7 +604,7 @@ mod tests { assert_eq!( sig.io(), ( - &vec![array_type(size, element_ty.clone()), USIZE_T].into(), + &vec![array_type(size, element_ty.clone()), usize_t()].into(), &vec![option_type(element_ty.clone()).into()].into() ) ); @@ -589,7 +613,7 @@ mod tests { #[test] fn test_set() { let size = 2; - let element_ty = BOOL_T; + let element_ty = bool_t(); let op = ArrayOpDef::set.to_concrete(element_ty.clone(), size); let optype: OpType = op.into(); @@ -600,7 +624,7 @@ mod tests { assert_eq!( sig.io(), ( - &vec![array_ty.clone(), USIZE_T, element_ty.clone()].into(), + &vec![array_ty.clone(), usize_t(), element_ty.clone()].into(), &vec![either_type(result_row.clone(), result_row).into()].into() ) ); @@ -609,7 +633,7 @@ mod tests { #[test] fn test_swap() { let size = 2; - let element_ty = BOOL_T; + let element_ty = bool_t(); let op = ArrayOpDef::swap.to_concrete(element_ty.clone(), size); let optype: OpType = op.into(); @@ -619,7 +643,7 @@ mod tests { assert_eq!( sig.io(), ( - &vec![array_ty.clone(), USIZE_T, USIZE_T].into(), + &vec![array_ty.clone(), usize_t(), usize_t()].into(), &vec![either_type(array_ty.clone(), array_ty).into()].into() ) ); @@ -628,7 +652,7 @@ mod tests { #[test] fn test_pops() { let size = 2; - let element_ty = BOOL_T; + let element_ty = bool_t(); for op in [ArrayOpDef::pop_left, ArrayOpDef::pop_right].iter() { let op = op.to_concrete(element_ty.clone(), size); @@ -653,7 +677,7 @@ mod tests { #[test] fn test_discard_empty() { let size = 0; - let element_ty = BOOL_T; + let element_ty = bool_t(); let op = ArrayOpDef::discard_empty.to_concrete(element_ty.clone(), size); let optype: OpType = op.into(); @@ -672,7 +696,7 @@ mod tests { #[test] fn test_repeat() { let size = 2; - let element_ty = QB_T; + let element_ty = qb_t(); let op = ArrayOpDef::repeat.to_concrete(element_ty.clone(), size); let optype: OpType = op.into(); @@ -682,7 +706,7 @@ mod tests { assert_eq!( sig.io(), ( - &vec![Type::new_function(Signature::new(vec![], vec![QB_T]))].into(), + &vec![Type::new_function(Signature::new(vec![], vec![qb_t()]))].into(), &vec![array_type(size, element_ty.clone())].into(), ) ); @@ -690,7 +714,7 @@ mod tests { #[test] fn test_scan_def() { - let op = ArrayScan::new(BOOL_T, QB_T, vec![USIZE_T], 2); + let op = ArrayScan::new(bool_t(), qb_t(), vec![usize_t()], 2); let optype: OpType = op.clone().into(); let new_op: ArrayScan = optype.cast().unwrap(); assert_eq!(new_op, op); @@ -699,8 +723,8 @@ mod tests { #[test] fn test_scan_map() { let size = 2; - let src_ty = QB_T; - let tgt_ty = BOOL_T; + let src_ty = qb_t(); + let tgt_ty = bool_t(); let op = ArrayScan::new(src_ty.clone(), tgt_ty.clone(), vec![], size); let optype: OpType = op.into(); @@ -722,10 +746,10 @@ mod tests { #[test] fn test_scan_accs() { let size = 2; - let src_ty = QB_T; - let tgt_ty = BOOL_T; - let acc_ty1 = USIZE_T; - let acc_ty2 = QB_T; + let src_ty = qb_t(); + let tgt_ty = bool_t(); + let acc_ty1 = usize_t(); + let acc_ty2 = qb_t(); let op = ArrayScan::new( src_ty.clone(), diff --git a/hugr-core/src/extension/prelude/unwrap_builder.rs b/hugr-core/src/extension/prelude/unwrap_builder.rs index 7d7f3f5b3..753533f1f 100644 --- a/hugr-core/src/extension/prelude/unwrap_builder.rs +++ b/hugr-core/src/extension/prelude/unwrap_builder.rs @@ -86,7 +86,7 @@ mod tests { use crate::{ builder::{DFGBuilder, DataflowHugr}, extension::{ - prelude::{option_type, BOOL_T}, + prelude::{bool_t, option_type}, PRELUDE_REGISTRY, }, types::Signature, @@ -94,14 +94,15 @@ mod tests { #[test] fn test_build_unwrap() { - let mut builder = - DFGBuilder::new(Signature::new(Type::from(option_type(BOOL_T)), BOOL_T).with_prelude()) - .unwrap(); + let mut builder = DFGBuilder::new( + Signature::new(Type::from(option_type(bool_t())), bool_t()).with_prelude(), + ) + .unwrap(); let [opt] = builder.input_wires_arr(); let [res] = builder - .build_unwrap_sum(&PRELUDE_REGISTRY, 1, option_type(BOOL_T), opt) + .build_unwrap_sum(&PRELUDE_REGISTRY, 1, option_type(bool_t()), opt) .unwrap(); builder.finish_prelude_hugr_with_outputs([res]).unwrap(); } diff --git a/hugr-core/src/extension/simple_op.rs b/hugr-core/src/extension/simple_op.rs index 6d1c678c5..d48f596ea 100644 --- a/hugr-core/src/extension/simple_op.rs +++ b/hugr-core/src/extension/simple_op.rs @@ -53,12 +53,24 @@ pub trait MakeOpDef: NamedOp { where Self: Sized; - /// Return the signature (polymorphic function type) of the operation. - fn signature(&self) -> SignatureFunc; - /// The ID of the extension this operation is defined in. fn extension(&self) -> ExtensionId; + /// Returns a weak reference to the extension this operation is defined in. + fn extension_ref(&self) -> Weak; + + /// Compute the signature of the operation while the extension definition is being built. + /// + /// Requires a [`Weak`] reference to the extension defining the operation. + /// This method is intended to be used inside the closure passed to [`Extension::new_arc`], + /// and it is normally internally called by [`MakeOpDef::add_to_extension`]. + fn init_signature(&self, extension_ref: &Weak) -> SignatureFunc; + + /// Return the signature (polymorphic function type) of the operation. + fn signature(&self) -> SignatureFunc { + self.init_signature(&self.extension_ref()) + } + /// Description of the operation. By default, the same as `self.name()`. fn description(&self) -> String { self.name().to_string() @@ -80,7 +92,7 @@ pub trait MakeOpDef: NamedOp { let def = extension.add_op( self.name(), self.description(), - self.signature(), + self.init_signature(extension_ref), extension_ref, )?; @@ -306,10 +318,14 @@ mod test { } impl MakeOpDef for DummyEnum { - fn signature(&self) -> SignatureFunc { + fn init_signature(&self, _extension_ref: &Weak) -> SignatureFunc { Signature::new_endo(type_row![]).into() } + fn extension_ref(&self) -> Weak { + Arc::downgrade(&EXT) + } + fn from_def(_op_def: &OpDef) -> Result { Ok(Self::Dumb) } diff --git a/hugr-core/src/extension/type_def.rs b/hugr-core/src/extension/type_def.rs index 7f0daa3ca..b15a8d3c3 100644 --- a/hugr-core/src/extension/type_def.rs +++ b/hugr-core/src/extension/type_def.rs @@ -127,6 +127,7 @@ impl TypeDef { args, self.extension_id().clone(), bound, + &self.extension_ref, )) } /// The [`TypeBound`] of the definition. @@ -223,9 +224,9 @@ impl Extension { #[cfg(test)] mod test { - use crate::extension::prelude::{QB_T, USIZE_T}; + use crate::extension::prelude::{qb_t, usize_t}; use crate::extension::SignatureError; - use crate::std_extensions::arithmetic::float_types::FLOAT64_TYPE; + use crate::std_extensions::arithmetic::float_types::float64_type; use crate::types::type_param::{TypeArg, TypeArgError, TypeParam}; use crate::types::{Signature, Type, TypeBound}; @@ -251,15 +252,15 @@ mod test { .unwrap(), ); assert_eq!(typ.least_upper_bound(), TypeBound::Copyable); - let typ2 = Type::new_extension(def.instantiate([USIZE_T.into()]).unwrap()); + let typ2 = Type::new_extension(def.instantiate([usize_t().into()]).unwrap()); assert_eq!(typ2.least_upper_bound(), TypeBound::Copyable); // And some bad arguments...firstly, wrong kind of TypeArg: assert_eq!( - def.instantiate([TypeArg::Type { ty: QB_T }]), + def.instantiate([TypeArg::Type { ty: qb_t() }]), Err(SignatureError::TypeArgMismatch( TypeArgError::TypeMismatch { - arg: TypeArg::Type { ty: QB_T }, + arg: TypeArg::Type { ty: qb_t() }, param: TypeBound::Copyable.into() } )) @@ -272,8 +273,8 @@ mod test { // Too many arguments: assert_eq!( def.instantiate([ - TypeArg::Type { ty: FLOAT64_TYPE }, - TypeArg::Type { ty: FLOAT64_TYPE }, + TypeArg::Type { ty: float64_type() }, + TypeArg::Type { ty: float64_type() }, ]) .unwrap_err(), SignatureError::TypeArgMismatch(TypeArgError::WrongNumberArgs(2, 1)) diff --git a/hugr-core/src/hugr/hugrmut.rs b/hugr-core/src/hugr/hugrmut.rs index 3d9edc050..4753e1dec 100644 --- a/hugr-core/src/hugr/hugrmut.rs +++ b/hugr-core/src/hugr/hugrmut.rs @@ -535,18 +535,15 @@ pub(super) fn panic_invalid_port( mod test { use crate::{ extension::{ - prelude::{Noop, USIZE_T}, + prelude::{usize_t, Noop}, PRELUDE_REGISTRY, }, - macros::type_row, ops::{self, dataflow::IOTrait, FuncDefn, Input, Output}, - types::{Signature, Type}, + types::Signature, }; use super::*; - const NAT: Type = USIZE_T; - #[test] fn simple_function() -> Result<(), Box> { let mut hugr = Hugr::default(); @@ -559,16 +556,16 @@ mod test { module, ops::FuncDefn { name: "main".into(), - signature: Signature::new(type_row![NAT], type_row![NAT, NAT]) + signature: Signature::new(vec![usize_t()], vec![usize_t(), usize_t()]) .with_prelude() .into(), }, ); { - let f_in = hugr.add_node_with_parent(f, ops::Input::new(type_row![NAT])); - let f_out = hugr.add_node_with_parent(f, ops::Output::new(type_row![NAT, NAT])); - let noop = hugr.add_node_with_parent(f, Noop(NAT)); + let f_in = hugr.add_node_with_parent(f, ops::Input::new(vec![usize_t()])); + let f_out = hugr.add_node_with_parent(f, ops::Output::new(vec![usize_t(), usize_t()])); + let noop = hugr.add_node_with_parent(f, Noop(usize_t())); hugr.connect(f_in, 0, noop, 0); hugr.connect(noop, 0, f_out, 0); @@ -608,11 +605,11 @@ mod test { root, FuncDefn { name: name.to_string(), - signature: Signature::new_endo(NAT).into(), + signature: Signature::new_endo(usize_t()).into(), }, ); - let inp = hugr.add_node_with_parent(fd, Input::new(NAT)); - let out = hugr.add_node_with_parent(fd, Output::new(NAT)); + let inp = hugr.add_node_with_parent(fd, Input::new(usize_t())); + let out = hugr.add_node_with_parent(fd, Output::new(usize_t())); hugr.connect(inp, 0, out, 0); fd }); diff --git a/hugr-core/src/hugr/rewrite/inline_dfg.rs b/hugr-core/src/hugr/rewrite/inline_dfg.rs index ad0b91dc3..6981c7277 100644 --- a/hugr-core/src/hugr/rewrite/inline_dfg.rs +++ b/hugr-core/src/hugr/rewrite/inline_dfg.rs @@ -136,7 +136,7 @@ mod test { endo_sig, inout_sig, Container, DFGBuilder, Dataflow, DataflowHugr, DataflowSubContainer, SubContainer, }; - use crate::extension::prelude::QB_T; + use crate::extension::prelude::qb_t; use crate::extension::{ExtensionRegistry, ExtensionSet, PRELUDE}; use crate::hugr::rewrite::inline_dfg::InlineDFGError; use crate::hugr::HugrMut; @@ -244,13 +244,13 @@ mod test { #[test] fn permutation() -> Result<(), Box> { - let mut h = DFGBuilder::new(endo_sig(type_row![QB_T, QB_T]))?; + let mut h = DFGBuilder::new(endo_sig(vec![qb_t(), qb_t()]))?; let [p, q] = h.input_wires_arr(); let [p_h] = h .add_dataflow_op(test_quantum_extension::h_gate(), [p])? .outputs_arr(); let swap = { - let swap = h.dfg_builder(Signature::new_endo(type_row![QB_T, QB_T]), [p_h, q])?; + let swap = h.dfg_builder(Signature::new_endo(vec![qb_t(), qb_t()]), [p_h, q])?; let [a, b] = swap.input_wires_arr(); swap.finish_with_outputs([b, a])? }; @@ -339,11 +339,11 @@ mod test { PRELUDE.to_owned(), ]) .unwrap(); - let mut outer = DFGBuilder::new(endo_sig(type_row![QB_T, QB_T]))?; + let mut outer = DFGBuilder::new(endo_sig(vec![qb_t(), qb_t()]))?; let [a, b] = outer.input_wires_arr(); let h_a = outer.add_dataflow_op(test_quantum_extension::h_gate(), [a])?; let h_b = outer.add_dataflow_op(test_quantum_extension::h_gate(), [b])?; - let mut inner = outer.dfg_builder(endo_sig(QB_T), h_b.outputs())?; + let mut inner = outer.dfg_builder(endo_sig(qb_t()), h_b.outputs())?; let [i] = inner.input_wires_arr(); let f = inner.add_load_value(float_types::ConstF64::new(1.0)); inner.add_other_wire(inner.input().node(), f.node()); diff --git a/hugr-core/src/hugr/rewrite/insert_identity.rs b/hugr-core/src/hugr/rewrite/insert_identity.rs index 6d8108b0c..cacd59591 100644 --- a/hugr-core/src/hugr/rewrite/insert_identity.rs +++ b/hugr-core/src/hugr/rewrite/insert_identity.rs @@ -102,7 +102,7 @@ mod tests { use super::super::simple_replace::test::dfg_hugr; use super::*; use crate::{ - extension::{prelude::QB_T, PRELUDE_REGISTRY}, + extension::{prelude::qb_t, PRELUDE_REGISTRY}, Hugr, }; @@ -127,7 +127,7 @@ mod tests { let noop: Noop = h.get_optype(noop_node).cast().unwrap(); - assert_eq!(noop, Noop(QB_T)); + assert_eq!(noop, Noop(qb_t())); h.update_validate(&PRELUDE_REGISTRY).unwrap(); } diff --git a/hugr-core/src/hugr/rewrite/outline_cfg.rs b/hugr-core/src/hugr/rewrite/outline_cfg.rs index 7dd181f92..1b9a47a1a 100644 --- a/hugr-core/src/hugr/rewrite/outline_cfg.rs +++ b/hugr-core/src/hugr/rewrite/outline_cfg.rs @@ -251,14 +251,14 @@ mod test { BlockBuilder, BuildError, CFGBuilder, Container, Dataflow, DataflowSubContainer, HugrBuilder, ModuleBuilder, }; - use crate::extension::prelude::USIZE_T; + use crate::extension::prelude::usize_t; use crate::extension::PRELUDE_REGISTRY; use crate::hugr::views::sibling::SiblingMut; use crate::hugr::HugrMut; use crate::ops::constant::Value; use crate::ops::handle::{BasicBlockID, CfgID, ConstID, NodeHandle}; use crate::types::Signature; - use crate::{type_row, Hugr, HugrView, Node}; + use crate::{Hugr, HugrView, Node}; use cool_asserts::assert_matches; use itertools::Itertools; use rstest::rstest; @@ -278,7 +278,7 @@ mod test { } impl CondThenLoopCfg { fn new() -> Result { - let block_ty = Signature::new_endo(USIZE_T); + let block_ty = Signature::new_endo(usize_t()); let mut cfg_builder = CFGBuilder::new(block_ty.clone())?; let pred_const = cfg_builder.add_constant(Value::unit_sum(0, 2).expect("0 < 2")); let const_unit = cfg_builder.add_constant(Value::unary_unit_sum()); @@ -295,7 +295,7 @@ mod test { }; let entry = n_identity( - cfg_builder.simple_entry_builder(USIZE_T.into(), 2)?, + cfg_builder.simple_entry_builder(usize_t().into(), 2)?, &pred_const, )?; @@ -311,7 +311,7 @@ mod test { let head = id_block(&mut cfg_builder)?; cfg_builder.branch(&merge, 0, &head)?; let tail = n_identity( - cfg_builder.simple_block_builder(Signature::new_endo(USIZE_T), 2)?, + cfg_builder.simple_block_builder(Signature::new_endo(usize_t()), 2)?, &pred_const, )?; cfg_builder.branch(&tail, 1, &head)?; @@ -439,10 +439,7 @@ mod test { // operating via a SiblingMut let mut module_builder = ModuleBuilder::new(); let mut fbuild = module_builder - .define_function( - "main", - Signature::new(type_row![USIZE_T], type_row![USIZE_T]), - ) + .define_function("main", Signature::new(vec![usize_t()], vec![usize_t()])) .unwrap(); let [i1] = fbuild.input_wires_arr(); let cfg = fbuild diff --git a/hugr-core/src/hugr/rewrite/replace.rs b/hugr-core/src/hugr/rewrite/replace.rs index e23fab7c5..ffdbb0743 100644 --- a/hugr-core/src/hugr/rewrite/replace.rs +++ b/hugr-core/src/hugr/rewrite/replace.rs @@ -451,7 +451,7 @@ mod test { endo_sig, BuildError, CFGBuilder, Container, DFGBuilder, Dataflow, DataflowHugr, DataflowSubContainer, HugrBuilder, SubContainer, }; - use crate::extension::prelude::{BOOL_T, USIZE_T}; + use crate::extension::prelude::{bool_t, usize_t}; use crate::extension::{ExtensionRegistry, PRELUDE, PRELUDE_REGISTRY}; use crate::hugr::internal::HugrMutInternals; use crate::hugr::rewrite::replace::WhichHugr; @@ -473,17 +473,17 @@ mod test { let reg = ExtensionRegistry::try_new([PRELUDE.to_owned(), collections::EXTENSION.to_owned()]) .unwrap(); - let listy = list_type(USIZE_T); + let listy = list_type(usize_t()); let pop: ExtensionOp = ListOp::pop - .with_type(USIZE_T) + .with_type(usize_t()) .to_extension_op(®) .unwrap(); let push: ExtensionOp = ListOp::push - .with_type(USIZE_T) + .with_type(usize_t()) .to_extension_op(®) .unwrap(); let just_list = TypeRow::from(vec![listy.clone()]); - let intermed = TypeRow::from(vec![listy.clone(), USIZE_T]); + let intermed = TypeRow::from(vec![listy.clone(), usize_t()]); let mut cfg = CFGBuilder::new(endo_sig(just_list.clone()))?; @@ -638,7 +638,7 @@ mod test { #[test] fn test_invalid() { - let utou = Signature::new_endo(vec![USIZE_T]); + let utou = Signature::new_endo(vec![usize_t()]); let ext = Extension::new_test_arc("new_ext".try_into().unwrap(), |ext, extension_ref| { ext.add_op("foo".into(), "".to_string(), utou.clone(), extension_ref) .unwrap(); @@ -659,7 +659,7 @@ mod test { .unwrap(); let mut h = DFGBuilder::new( - Signature::new(type_row![USIZE_T, BOOL_T], type_row![USIZE_T]) + Signature::new(vec![usize_t(), bool_t()], vec![usize_t()]) .with_extension_delta(ext_name.clone()), ) .unwrap(); @@ -667,8 +667,8 @@ mod test { let mut cond = h .conditional_builder_exts( (vec![type_row![]; 2], b), - [(USIZE_T, i)], - type_row![USIZE_T], + [(usize_t(), i)], + vec![usize_t()].into(), ext_name.clone(), ) .unwrap(); diff --git a/hugr-core/src/hugr/rewrite/simple_replace.rs b/hugr-core/src/hugr/rewrite/simple_replace.rs index c07fefe93..422875275 100644 --- a/hugr-core/src/hugr/rewrite/simple_replace.rs +++ b/hugr-core/src/hugr/rewrite/simple_replace.rs @@ -242,7 +242,7 @@ pub(in crate::hugr::rewrite) mod test { endo_sig, inout_sig, BuildError, Container, DFGBuilder, Dataflow, DataflowHugr, DataflowSubContainer, HugrBuilder, ModuleBuilder, }; - use crate::extension::prelude::{BOOL_T, QB_T}; + use crate::extension::prelude::{bool_t, qb_t}; use crate::extension::{ExtensionSet, EMPTY_REG, PRELUDE_REGISTRY}; use crate::hugr::views::{HugrView, SiblingSubgraph}; use crate::hugr::{Hugr, HugrMut, Rewrite}; @@ -252,15 +252,12 @@ pub(in crate::hugr::rewrite) mod test { use crate::ops::OpTrait; use crate::std_extensions::logic::test::and_op; use crate::std_extensions::logic::LogicOp; - use crate::type_row; use crate::types::{Signature, Type}; use crate::utils::test_quantum_extension::{cx_gate, h_gate, EXTENSION_ID}; use crate::{IncomingPort, Node}; use super::SimpleReplacement; - const QB: Type = crate::extension::prelude::QB_T; - /// Creates a hugr like the following: /// -- H -- /// -- [DFG] -- @@ -276,14 +273,16 @@ pub(in crate::hugr::rewrite) mod test { let just_q: ExtensionSet = EXTENSION_ID.into(); let mut func_builder = module_builder.define_function( "main", - Signature::new_endo(type_row![QB, QB, QB]).with_extension_delta(just_q.clone()), + Signature::new_endo(vec![qb_t(), qb_t(), qb_t()]) + .with_extension_delta(just_q.clone()), )?; let [qb0, qb1, qb2] = func_builder.input_wires_arr(); let q_out = func_builder.add_dataflow_op(h_gate(), vec![qb2])?; - let mut inner_builder = func_builder.dfg_builder_endo([(QB, qb0), (QB, qb1)])?; + let mut inner_builder = + func_builder.dfg_builder_endo([(qb_t(), qb0), (qb_t(), qb1)])?; let inner_graph = { let [wire0, wire1] = inner_builder.input_wires_arr(); let wire2 = inner_builder.add_dataflow_op(h_gate(), vec![wire0])?; @@ -312,7 +311,7 @@ pub(in crate::hugr::rewrite) mod test { /// ┤ H ├┤ X ├ /// └───┘└───┘ fn make_dfg_hugr() -> Result { - let mut dfg_builder = DFGBuilder::new(endo_sig(type_row![QB, QB]).with_prelude())?; + let mut dfg_builder = DFGBuilder::new(endo_sig(vec![qb_t(), qb_t()]).with_prelude())?; let [wire0, wire1] = dfg_builder.input_wires_arr(); let wire2 = dfg_builder.add_dataflow_op(h_gate(), vec![wire0])?; let wire3 = dfg_builder.add_dataflow_op(h_gate(), vec![wire1])?; @@ -332,7 +331,7 @@ pub(in crate::hugr::rewrite) mod test { /// ┤ H ├ /// └───┘ fn make_dfg_hugr2() -> Result { - let mut dfg_builder = DFGBuilder::new(endo_sig(type_row![QB, QB]))?; + let mut dfg_builder = DFGBuilder::new(endo_sig(vec![qb_t(), qb_t()]))?; let [wire0, wire1] = dfg_builder.input_wires_arr(); let wire2 = dfg_builder.add_dataflow_op(h_gate(), vec![wire1])?; @@ -346,7 +345,7 @@ pub(in crate::hugr::rewrite) mod test { make_dfg_hugr2().unwrap() } - /// A hugr with a DFG root mapping BOOL_T to (BOOL_T, BOOL_T) + /// A hugr with a DFG root mapping bool_t() to (bool_t(), bool_t()) /// ┌─────────┐ /// ┌────┤ (1) NOT ├── /// ┌─────────┐ │ └─────────┘ @@ -360,7 +359,7 @@ pub(in crate::hugr::rewrite) mod test { #[fixture] pub(in crate::hugr::rewrite) fn dfg_hugr_copy_bools() -> (Hugr, Vec) { let mut dfg_builder = - DFGBuilder::new(inout_sig(type_row![BOOL_T], type_row![BOOL_T, BOOL_T])).unwrap(); + DFGBuilder::new(inout_sig(vec![bool_t()], vec![bool_t(), bool_t()])).unwrap(); let [b] = dfg_builder.input_wires_arr(); let not_inp = dfg_builder.add_dataflow_op(LogicOp::Not, vec![b]).unwrap(); @@ -379,7 +378,7 @@ pub(in crate::hugr::rewrite) mod test { ) } - /// A hugr with a DFG root mapping BOOL_T to (BOOL_T, BOOL_T) + /// A hugr with a DFG root mapping bool_t() to (bool_t(), bool_t()) /// ┌─────────┐ /// ┌────┤ (1) NOT ├── /// ┌─────────┐ │ └─────────┘ @@ -393,7 +392,7 @@ pub(in crate::hugr::rewrite) mod test { #[fixture] pub(in crate::hugr::rewrite) fn dfg_hugr_half_not_bools() -> (Hugr, Vec) { let mut dfg_builder = - DFGBuilder::new(inout_sig(type_row![BOOL_T], type_row![BOOL_T, BOOL_T])).unwrap(); + DFGBuilder::new(inout_sig(vec![bool_t()], vec![bool_t(), bool_t()])).unwrap(); let [b] = dfg_builder.input_wires_arr(); let not_inp = dfg_builder.add_dataflow_op(LogicOp::Not, vec![b]).unwrap(); @@ -567,7 +566,7 @@ pub(in crate::hugr::rewrite) mod test { #[test] fn test_replace_cx_cross() { - let q_row: Vec = vec![QB, QB]; + let q_row: Vec = vec![qb_t(), qb_t()]; let mut builder = DFGBuilder::new(endo_sig(q_row)).unwrap(); let mut circ = builder.as_circuit(builder.input_wires()); circ.append(cx_gate(), [0, 1]).unwrap(); @@ -623,8 +622,8 @@ pub(in crate::hugr::rewrite) mod test { #[test] fn test_replace_after_copy() { - let one_bit = type_row![BOOL_T]; - let two_bit = type_row![BOOL_T, BOOL_T]; + let one_bit = vec![bool_t()]; + let two_bit = vec![bool_t(), bool_t()]; let mut builder = DFGBuilder::new(endo_sig(one_bit.clone())).unwrap(); let inw = builder.input_wires().exactly_one().unwrap(); @@ -685,8 +684,8 @@ pub(in crate::hugr::rewrite) mod test { let [_input, output] = hugr.get_io(hugr.root()).unwrap(); let replacement = { - let b = DFGBuilder::new(Signature::new(type_row![BOOL_T], type_row![BOOL_T, BOOL_T])) - .unwrap(); + let b = + DFGBuilder::new(Signature::new(vec![bool_t()], vec![bool_t(), bool_t()])).unwrap(); let [w] = b.input_wires_arr(); b.finish_prelude_hugr_with_outputs([w, w]).unwrap() }; @@ -743,7 +742,7 @@ pub(in crate::hugr::rewrite) mod test { let (replacement, repl_not) = { let mut b = - DFGBuilder::new(inout_sig(type_row![BOOL_T], type_row![BOOL_T, BOOL_T])).unwrap(); + DFGBuilder::new(inout_sig(vec![bool_t()], vec![bool_t(), bool_t()])).unwrap(); let [w] = b.input_wires_arr(); let not = b.add_dataflow_op(LogicOp::Not, vec![w]).unwrap(); let [w_not] = not.outputs_arr(); @@ -802,9 +801,9 @@ pub(in crate::hugr::rewrite) mod test { .unwrap(); // build a nested identity dfg - let mut nest_build = DFGBuilder::new(Signature::new_endo(QB_T)).unwrap(); + let mut nest_build = DFGBuilder::new(Signature::new_endo(qb_t())).unwrap(); let [input] = nest_build.input_wires_arr(); - let inner_build = nest_build.dfg_builder_endo([(QB_T, input)]).unwrap(); + let inner_build = nest_build.dfg_builder_endo([(qb_t(), input)]).unwrap(); let inner_dfg = n_identity(inner_build).unwrap(); let inner_dfg_node = inner_dfg.node(); let replacement = nest_build diff --git a/hugr-core/src/hugr/serialize/test.rs b/hugr-core/src/hugr/serialize/test.rs index 5afd19cd4..d5fdd1858 100644 --- a/hugr-core/src/hugr/serialize/test.rs +++ b/hugr-core/src/hugr/serialize/test.rs @@ -6,14 +6,14 @@ use crate::builder::{ DataflowSubContainer, HugrBuilder, ModuleBuilder, }; use crate::extension::prelude::Noop; -use crate::extension::prelude::{BOOL_T, PRELUDE_ID, QB_T, USIZE_T}; +use crate::extension::prelude::{bool_t, qb_t, usize_t, PRELUDE_ID}; use crate::extension::simple_op::MakeRegisteredOp; use crate::extension::{test::SimpleOpDef, ExtensionSet, EMPTY_REG, PRELUDE_REGISTRY}; use crate::hugr::internal::HugrMutInternals; use crate::hugr::validate::ValidationError; use crate::ops::custom::{ExtensionOp, OpaqueOp, OpaqueOpError}; use crate::ops::{self, dataflow::IOTrait, Input, Module, Output, Value, DFG}; -use crate::std_extensions::arithmetic::float_types::FLOAT64_TYPE; +use crate::std_extensions::arithmetic::float_types::float64_type; use crate::std_extensions::arithmetic::int_ops::INT_OPS_REGISTRY; use crate::std_extensions::arithmetic::int_types::{ConstInt, INT_TYPES}; use crate::std_extensions::logic::LogicOp; @@ -31,9 +31,6 @@ use portgraph::LinkView; use portgraph::{multiportgraph::MultiPortGraph, Hierarchy, LinkMut, PortMut, UnmanagedDenseMap}; use rstest::rstest; -const NAT: Type = crate::extension::prelude::USIZE_T; -const QB: Type = crate::extension::prelude::QB_T; - /// Version 1 of the Testing HUGR serialization format, see `testing_hugr.py`. #[derive(Serialize, Deserialize, PartialEq, Debug, Default)] struct SerTestingLatest { @@ -248,11 +245,11 @@ fn gen_optype(g: &MultiPortGraph, node: portgraph::NodeIndex) -> OpType { let outputs = g.num_outputs(node); match (inputs == 0, outputs == 0) { (false, false) => DFG { - signature: Signature::new(vec![NAT; inputs - 1], vec![NAT; outputs - 1]), + signature: Signature::new(vec![usize_t(); inputs - 1], vec![usize_t(); outputs - 1]), } .into(), - (true, false) => Input::new(vec![NAT; outputs - 1]).into(), - (false, true) => Output::new(vec![NAT; inputs - 1]).into(), + (true, false) => Input::new(vec![usize_t(); outputs - 1]).into(), + (false, true) => Output::new(vec![usize_t(); inputs - 1]).into(), (true, true) => Module::new().into(), } } @@ -300,7 +297,7 @@ fn weighted_hugr_ser() { let mut module_builder = ModuleBuilder::new(); module_builder.set_metadata("name", "test"); - let t_row = vec![Type::new_sum([type_row![NAT], type_row![QB]])]; + let t_row = vec![Type::new_sum([vec![usize_t()], vec![qb_t()]])]; let mut f_build = module_builder .define_function("main", Signature::new(t_row.clone(), t_row).with_prelude()) .unwrap(); @@ -325,11 +322,14 @@ fn weighted_hugr_ser() { #[test] fn dfg_roundtrip() -> Result<(), Box> { - let tp: Vec = vec![BOOL_T; 2]; + let tp: Vec = vec![bool_t(); 2]; let mut dfg = DFGBuilder::new(Signature::new(tp.clone(), tp).with_prelude())?; let mut params: [_; 2] = dfg.input_wires_arr(); for p in params.iter_mut() { - *p = dfg.add_dataflow_op(Noop(BOOL_T), [*p]).unwrap().out_wire(0); + *p = dfg + .add_dataflow_op(Noop(bool_t()), [*p]) + .unwrap() + .out_wire(0); } let hugr = dfg.finish_hugr_with_outputs(params, &EMPTY_REG)?; @@ -339,7 +339,7 @@ fn dfg_roundtrip() -> Result<(), Box> { #[test] fn extension_ops() -> Result<(), Box> { - let tp: Vec = vec![BOOL_T; 1]; + let tp: Vec = vec![bool_t(); 1]; let mut dfg = DFGBuilder::new(endo_sig(tp))?; let [wire] = dfg.input_wires_arr(); @@ -358,7 +358,7 @@ fn extension_ops() -> Result<(), Box> { #[test] fn opaque_ops() -> Result<(), Box> { - let tp: Vec = vec![BOOL_T; 1]; + let tp: Vec = vec![bool_t(); 1]; let mut dfg = DFGBuilder::new(endo_sig(tp))?; let [wire] = dfg.input_wires_arr(); @@ -389,7 +389,7 @@ fn opaque_ops() -> Result<(), Box> { #[test] fn function_type() -> Result<(), Box> { - let fn_ty = Type::new_function(Signature::new_endo(type_row![BOOL_T]).with_prelude()); + let fn_ty = Type::new_function(Signature::new_endo(vec![bool_t()]).with_prelude()); let mut bldr = DFGBuilder::new(Signature::new_endo(vec![fn_ty.clone()]).with_prelude())?; let op = bldr.add_dataflow_op(Noop(fn_ty), bldr.input_wires())?; let h = bldr.finish_prelude_hugr_with_outputs(op.outputs())?; @@ -400,12 +400,12 @@ fn function_type() -> Result<(), Box> { #[test] fn hierarchy_order() -> Result<(), Box> { - let mut hugr = closed_dfg_root_hugr(Signature::new(vec![QB], vec![QB])); + let mut hugr = closed_dfg_root_hugr(Signature::new(vec![qb_t()], vec![qb_t()])); let [old_in, out] = hugr.get_io(hugr.root()).unwrap(); hugr.connect(old_in, 0, out, 0); // Now add a new input - let new_in = hugr.add_node(Input::new([QB].to_vec()).into()); + let new_in = hugr.add_node(Input::new([qb_t()].to_vec()).into()); hugr.disconnect(old_in, OutgoingPort::from(0)); hugr.connect(new_in, 0, out, 0); hugr.move_before_sibling(new_in, old_in); @@ -438,11 +438,11 @@ fn serialize_types_roundtrip() { check_testing_roundtrip(g.clone()); // A Simple tuple - let t = Type::new_tuple(vec![USIZE_T, g]); + let t = Type::new_tuple(vec![usize_t(), g]); check_testing_roundtrip(t); // A Classic sum - let t = TypeRV::new_sum([type_row![USIZE_T], type_row![FLOAT64_TYPE]]); + let t = TypeRV::new_sum([vec![usize_t()], vec![float64_type()]]); check_testing_roundtrip(t); let t = Type::new_unit_sum(4); @@ -450,21 +450,21 @@ fn serialize_types_roundtrip() { } #[rstest] -#[case(BOOL_T)] -#[case(USIZE_T)] +#[case(bool_t())] +#[case(usize_t())] #[case(INT_TYPES[2].clone())] #[case(Type::new_alias(crate::ops::AliasDecl::new("t", TypeBound::Any)))] #[case(Type::new_var_use(2, TypeBound::Copyable))] -#[case(Type::new_tuple(type_row![BOOL_T,QB_T]))] -#[case(Type::new_sum([type_row![BOOL_T,QB_T], type_row![Type::new_unit_sum(4)]]))] -#[case(Type::new_function(Signature::new_endo(type_row![QB_T,BOOL_T,USIZE_T])))] +#[case(Type::new_tuple(vec![bool_t(),qb_t()]))] +#[case(Type::new_sum([vec![bool_t(),qb_t()], vec![Type::new_unit_sum(4)]]))] +#[case(Type::new_function(Signature::new_endo(vec![qb_t(),bool_t(),usize_t()])))] fn roundtrip_type(#[case] typ: Type) { check_testing_roundtrip(typ); } #[rstest] #[case(SumType::new_unary(2))] -#[case(SumType::new([type_row![USIZE_T, QB_T], type_row![]]))] +#[case(SumType::new([vec![usize_t(), qb_t()].into(), type_row![]]))] fn roundtrip_sumtype(#[case] sum_type: SumType) { check_testing_roundtrip(sum_type); } @@ -506,8 +506,8 @@ fn polyfunctype2() -> PolyFuncTypeRV { #[rstest] #[case(Signature::new_endo(type_row![]).into())] #[case(polyfunctype1())] -#[case(PolyFuncType::new([TypeParam::String], Signature::new_endo(type_row![Type::new_var_use(0, TypeBound::Copyable)])))] -#[case(PolyFuncType::new([TypeBound::Copyable.into()], Signature::new_endo(type_row![Type::new_var_use(0, TypeBound::Copyable)])))] +#[case(PolyFuncType::new([TypeParam::String], Signature::new_endo(vec![Type::new_var_use(0, TypeBound::Copyable)])))] +#[case(PolyFuncType::new([TypeBound::Copyable.into()], Signature::new_endo(vec![Type::new_var_use(0, TypeBound::Copyable)])))] #[case(PolyFuncType::new([TypeParam::new_list(TypeBound::Any)], Signature::new_endo(type_row![])))] #[case(PolyFuncType::new([TypeParam::Tuple { params: [TypeBound::Any.into(), TypeParam::bounded_nat(2.try_into().unwrap())].into() }], Signature::new_endo(type_row![])))] #[case(PolyFuncType::new( @@ -519,8 +519,8 @@ fn roundtrip_polyfunctype_fixedlen(#[case] poly_func_type: PolyFuncType) { #[rstest] #[case(FuncValueType::new_endo(type_row![]).into())] -#[case(PolyFuncTypeRV::new([TypeParam::String], FuncValueType::new_endo(type_row![Type::new_var_use(0, TypeBound::Copyable)])))] -#[case(PolyFuncTypeRV::new([TypeBound::Copyable.into()], FuncValueType::new_endo(type_row![Type::new_var_use(0, TypeBound::Copyable)])))] +#[case(PolyFuncTypeRV::new([TypeParam::String], FuncValueType::new_endo(vec![Type::new_var_use(0, TypeBound::Copyable)])))] +#[case(PolyFuncTypeRV::new([TypeBound::Copyable.into()], FuncValueType::new_endo(vec![Type::new_var_use(0, TypeBound::Copyable)])))] #[case(PolyFuncTypeRV::new([TypeParam::new_list(TypeBound::Any)], FuncValueType::new_endo(type_row![])))] #[case(PolyFuncTypeRV::new([TypeParam::Tuple { params: [TypeBound::Any.into(), TypeParam::bounded_nat(2.try_into().unwrap())].into() }], FuncValueType::new_endo(type_row![])))] #[case(PolyFuncTypeRV::new( @@ -539,10 +539,10 @@ fn roundtrip_polyfunctype_varlen(#[case] poly_func_type: PolyFuncTypeRV) { #[case(ops::AliasDecl { name: "aliasdecl".into(), bound: TypeBound::Any})] #[case(ops::Const::new(Value::false_val()))] #[case(ops::Const::new(Value::function(crate::builder::test::simple_dfg_hugr()).unwrap()))] -#[case(ops::Input::new(type_row![Type::new_var_use(3,TypeBound::Copyable)]))] +#[case(ops::Input::new(vec![Type::new_var_use(3,TypeBound::Copyable)]))] #[case(ops::Output::new(vec![Type::new_function(FuncValueType::new_endo(type_row![]))]))] #[case(ops::Call::try_new(polyfunctype1(), [TypeArg::BoundedNat{n: 1}, TypeArg::Extensions{ es: ExtensionSet::singleton(&PRELUDE_ID)} ], &EMPTY_REG).unwrap())] -#[case(ops::CallIndirect { signature : Signature::new_endo(type_row![BOOL_T]) })] +#[case(ops::CallIndirect { signature : Signature::new_endo(vec![bool_t()]) })] fn roundtrip_optype(#[case] optype: impl Into + std::fmt::Debug) { check_testing_roundtrip(NodeSer { parent: portgraph::NodeIndex::new(0).into(), diff --git a/hugr-core/src/hugr/serialize/upgrade/test.rs b/hugr-core/src/hugr/serialize/upgrade/test.rs index 16449afdc..d08dea520 100644 --- a/hugr-core/src/hugr/serialize/upgrade/test.rs +++ b/hugr-core/src/hugr/serialize/upgrade/test.rs @@ -1,9 +1,8 @@ use crate::{ builder::{DFGBuilder, Dataflow, DataflowHugr}, - extension::prelude::BOOL_T, + extension::prelude::bool_t, hugr::serialize::test::check_hugr_deserialize, std_extensions::logic::LogicOp, - type_row, types::Signature, }; use lazy_static::lazy_static; @@ -47,7 +46,7 @@ pub fn empty_hugr() -> Hugr { #[once] pub fn hugr_with_named_op() -> Hugr { let mut builder = - DFGBuilder::new(Signature::new(type_row![BOOL_T, BOOL_T], type_row![BOOL_T])).unwrap(); + DFGBuilder::new(Signature::new(vec![bool_t(), bool_t()], vec![bool_t()])).unwrap(); let [a, b] = builder.input_wires_arr(); let x = builder.add_dataflow_op(LogicOp::And, [a, b]).unwrap(); builder diff --git a/hugr-core/src/hugr/validate/test.rs b/hugr-core/src/hugr/validate/test.rs index 97ffc3d53..9be6103a5 100644 --- a/hugr-core/src/hugr/validate/test.rs +++ b/hugr-core/src/hugr/validate/test.rs @@ -11,7 +11,7 @@ use crate::builder::{ FunctionBuilder, HugrBuilder, ModuleBuilder, SubContainer, }; use crate::extension::prelude::Noop; -use crate::extension::prelude::{BOOL_T, PRELUDE, PRELUDE_ID, QB_T, USIZE_T}; +use crate::extension::prelude::{bool_t, qb_t, usize_t, PRELUDE, PRELUDE_ID}; use crate::extension::{Extension, ExtensionSet, TypeDefBound, EMPTY_REG, PRELUDE_REGISTRY}; use crate::hugr::internal::HugrMutInternals; use crate::hugr::HugrMut; @@ -30,15 +30,13 @@ use crate::{ const_extension_ids, test_file, type_row, Direction, IncomingPort, Node, OutgoingPort, }; -const NAT: Type = crate::extension::prelude::USIZE_T; - /// Creates a hugr with a single function definition that copies a bit `copies` times. /// /// Returns the hugr and the node index of the definition. fn make_simple_hugr(copies: usize) -> (Hugr, Node) { let def_op: OpType = ops::FuncDefn { name: "main".into(), - signature: Signature::new(type_row![BOOL_T], vec![BOOL_T; copies]) + signature: Signature::new(vec![bool_t()], vec![bool_t(); copies]) .with_prelude() .into(), } @@ -53,13 +51,13 @@ fn make_simple_hugr(copies: usize) -> (Hugr, Node) { (b, def) } -/// Adds an input{BOOL_T}, copy{BOOL_T -> BOOL_T^copies}, and output{BOOL_T^copies} operation to a dataflow container. +/// Adds an input{bool_t()}, copy{bool_t() -> bool_t()^copies}, and output{bool_t()^copies} operation to a dataflow container. /// /// Returns the node indices of each of the operations. fn add_df_children(b: &mut Hugr, parent: Node, copies: usize) -> (Node, Node, Node) { - let input = b.add_node_with_parent(parent, ops::Input::new(type_row![BOOL_T])); - let output = b.add_node_with_parent(parent, ops::Output::new(vec![BOOL_T; copies])); - let copy = b.add_node_with_parent(parent, Noop(BOOL_T)); + let input = b.add_node_with_parent(parent, ops::Input::new(vec![bool_t()])); + let output = b.add_node_with_parent(parent, ops::Output::new(vec![bool_t(); copies])); + let copy = b.add_node_with_parent(parent, Noop(bool_t())); b.connect(input, 0, copy, 0); for i in 0..copies { @@ -113,7 +111,7 @@ fn invalid_root() { #[test] fn leaf_root() { - let leaf_op: OpType = Noop(USIZE_T).into(); + let leaf_op: OpType = Noop(usize_t()).into(); let b = Hugr::new(leaf_op); assert_eq!(b.validate(&PRELUDE_REGISTRY), Ok(())); @@ -122,7 +120,7 @@ fn leaf_root() { #[test] fn dfg_root() { let dfg_op: OpType = ops::DFG { - signature: Signature::new_endo(type_row![BOOL_T]).with_prelude(), + signature: Signature::new_endo(vec![bool_t()]).with_prelude(), } .into(); @@ -151,7 +149,7 @@ fn children_restrictions() { .unwrap(); // Add a definition without children - let def_sig = Signature::new(type_row![BOOL_T], type_row![BOOL_T, BOOL_T]); + let def_sig = Signature::new(vec![bool_t()], vec![bool_t(), bool_t()]); let new_def = b.add_node_with_parent( root, ops::FuncDefn { @@ -194,25 +192,25 @@ fn df_children_restrictions() { .unwrap(); // Replace the output operation of the df subgraph with a copy - b.replace_op(output, Noop(NAT)).unwrap(); + b.replace_op(output, Noop(usize_t())).unwrap(); assert_matches!( b.validate(&EMPTY_REG), Err(ValidationError::InvalidInitialChild { parent, .. }) => assert_eq!(parent, def) ); // Revert it back to an output, but with the wrong number of ports - b.replace_op(output, ops::Output::new(type_row![BOOL_T])) + b.replace_op(output, ops::Output::new(vec![bool_t()])) .unwrap(); assert_matches!( b.validate(&EMPTY_REG), Err(ValidationError::InvalidChildren { parent, source: ChildrenValidationError::IOSignatureMismatch { child, .. }, .. }) => {assert_eq!(parent, def); assert_eq!(child, output.pg_index())} ); - b.replace_op(output, ops::Output::new(type_row![BOOL_T, BOOL_T])) + b.replace_op(output, ops::Output::new(vec![bool_t(), bool_t()])) .unwrap(); // After fixing the output back, replace the copy with an output op - b.replace_op(copy, ops::Output::new(type_row![BOOL_T, BOOL_T])) + b.replace_op(copy, ops::Output::new(vec![bool_t(), bool_t()])) .unwrap(); assert_matches!( b.validate(&EMPTY_REG), @@ -224,22 +222,22 @@ fn df_children_restrictions() { #[test] fn test_ext_edge() { let mut h = closed_dfg_root_hugr( - Signature::new(type_row![BOOL_T, BOOL_T], type_row![BOOL_T]) + Signature::new(vec![bool_t(), bool_t()], vec![bool_t()]) .with_extension_delta(TO_BE_INFERRED), ); let [input, output] = h.get_io(h.root()).unwrap(); - // Nested DFG BOOL_T -> BOOL_T + // Nested DFG bool_t() -> bool_t() let sub_dfg = h.add_node_with_parent( h.root(), ops::DFG { - signature: Signature::new_endo(type_row![BOOL_T]).with_extension_delta(TO_BE_INFERRED), + signature: Signature::new_endo(vec![bool_t()]).with_extension_delta(TO_BE_INFERRED), }, ); // this Xor has its 2nd input unconnected let sub_op = { - let sub_input = h.add_node_with_parent(sub_dfg, ops::Input::new(type_row![BOOL_T])); - let sub_output = h.add_node_with_parent(sub_dfg, ops::Output::new(type_row![BOOL_T])); + let sub_input = h.add_node_with_parent(sub_dfg, ops::Input::new(vec![bool_t()])); + let sub_output = h.add_node_with_parent(sub_dfg, ops::Output::new(vec![bool_t()])); let sub_op = h.add_node_with_parent(sub_dfg, and_op()); h.connect(sub_input, 0, sub_op, 0); h.connect(sub_op, 0, sub_output, 0); @@ -268,8 +266,8 @@ fn test_ext_edge() { #[test] fn no_ext_edge_into_func() -> Result<(), Box> { - let b2b = Signature::new_endo(BOOL_T); - let mut h = DFGBuilder::new(Signature::new(BOOL_T, Type::new_function(b2b.clone())))?; + let b2b = Signature::new_endo(bool_t()); + let mut h = DFGBuilder::new(Signature::new(bool_t(), Type::new_function(b2b.clone())))?; let [input] = h.input_wires_arr(); let mut dfg = h.dfg_builder(Signature::new(vec![], Type::new_function(b2b.clone())), [])?; @@ -298,7 +296,7 @@ fn no_ext_edge_into_func() -> Result<(), Box> { #[test] fn test_local_const() { let mut h = - closed_dfg_root_hugr(Signature::new_endo(BOOL_T).with_extension_delta(TO_BE_INFERRED)); + closed_dfg_root_hugr(Signature::new_endo(bool_t()).with_extension_delta(TO_BE_INFERRED)); let [input, output] = h.get_io(h.root()).unwrap(); let and = h.add_node_with_parent(h.root(), and_op()); h.connect(input, 0, and, 0); @@ -308,7 +306,7 @@ fn test_local_const() { Err(ValidationError::UnconnectedPort { node: and, port: IncomingPort::from(1).into(), - port_kind: EdgeKind::Value(BOOL_T) + port_kind: EdgeKind::Value(bool_t()) }) ); let const_op: ops::Const = logic::EXTENSION @@ -319,7 +317,7 @@ fn test_local_const() { .into(); // Second input of Xor from a constant let cst = h.add_node_with_parent(h.root(), const_op); - let lcst = h.add_node_with_parent(h.root(), ops::LoadConstant { datatype: BOOL_T }); + let lcst = h.add_node_with_parent(h.root(), ops::LoadConstant { datatype: bool_t() }); h.connect(cst, 0, lcst, 0); h.connect(lcst, 0, and, 1); @@ -330,7 +328,7 @@ fn test_local_const() { #[test] fn dfg_with_cycles() { - let mut h = closed_dfg_root_hugr(Signature::new(type_row![BOOL_T, BOOL_T], type_row![BOOL_T])); + let mut h = closed_dfg_root_hugr(Signature::new(vec![bool_t(), bool_t()], vec![bool_t()])); let [input, output] = h.get_io(h.root()).unwrap(); let or = h.add_node_with_parent(h.root(), or_op()); let not1 = h.add_node_with_parent(h.root(), LogicOp::Not); @@ -363,7 +361,7 @@ fn identity_hugr_with_type(t: Type) -> (Hugr, Node) { } #[test] fn unregistered_extension() { - let (mut h, def) = identity_hugr_with_type(USIZE_T); + let (mut h, def) = identity_hugr_with_type(usize_t()); assert_eq!( h.validate(&EMPTY_REG), Err(ValidationError::SignatureError { @@ -389,7 +387,7 @@ fn invalid_types() { ) .unwrap(); }); - let reg = ExtensionRegistry::try_new([ext, PRELUDE.clone()]).unwrap(); + let reg = ExtensionRegistry::try_new([ext.clone(), PRELUDE.clone()]).unwrap(); let validate_to_sig_error = |t: CustomType| { let (h, def) = identity_hugr_with_type(Type::new_extension(t)); @@ -407,9 +405,10 @@ fn invalid_types() { let valid = Type::new_extension(CustomType::new( "MyContainer", - vec![TypeArg::Type { ty: USIZE_T }], + vec![TypeArg::Type { ty: usize_t() }], EXT_ID, TypeBound::Any, + &Arc::downgrade(&ext), )); assert_eq!( identity_hugr_with_type(valid.clone()) @@ -424,6 +423,7 @@ fn invalid_types() { vec![TypeArg::Type { ty: valid.clone() }], EXT_ID, TypeBound::Any, + &Arc::downgrade(&ext), ); assert_eq!( validate_to_sig_error(element_outside_bound), @@ -435,9 +435,10 @@ fn invalid_types() { let bad_bound = CustomType::new( "MyContainer", - vec![TypeArg::Type { ty: USIZE_T }], + vec![TypeArg::Type { ty: usize_t() }], EXT_ID, TypeBound::Copyable, + &Arc::downgrade(&ext), ); assert_eq!( validate_to_sig_error(bad_bound.clone()), @@ -455,6 +456,7 @@ fn invalid_types() { }], EXT_ID, TypeBound::Any, + &Arc::downgrade(&ext), ); assert_eq!( validate_to_sig_error(nested), @@ -466,9 +468,13 @@ fn invalid_types() { let too_many_type_args = CustomType::new( "MyContainer", - vec![TypeArg::Type { ty: USIZE_T }, TypeArg::BoundedNat { n: 3 }], + vec![ + TypeArg::Type { ty: usize_t() }, + TypeArg::BoundedNat { n: 3 }, + ], EXT_ID, TypeBound::Any, + &Arc::downgrade(&ext), ); assert_eq!( validate_to_sig_error(too_many_type_args), @@ -622,15 +628,15 @@ pub(crate) fn extension_with_eval_parallel() -> Arc { #[test] fn instantiate_row_variables() -> Result<(), Box> { fn uint_seq(i: usize) -> TypeArg { - vec![TypeArg::Type { ty: USIZE_T }; i].into() + vec![TypeArg::Type { ty: usize_t() }; i].into() } let e = extension_with_eval_parallel(); let mut dfb = DFGBuilder::new(inout_sig( vec![ - Type::new_function(Signature::new(USIZE_T, vec![USIZE_T, USIZE_T])), - USIZE_T, + Type::new_function(Signature::new(usize_t(), vec![usize_t(), usize_t()])), + usize_t(), ], // inputs: function + its argument - vec![USIZE_T; 4], // outputs (*2^2, three calls) + vec![usize_t(); 4], // outputs (*2^2, three calls) ))?; let [func, int] = dfb.input_wires_arr(); let eval = e.instantiate_extension_op("eval", [uint_seq(1), uint_seq(2)], &PRELUDE_REGISTRY)?; @@ -662,7 +668,7 @@ fn row_variables() -> Result<(), Box> { let e = extension_with_eval_parallel(); let tv = TypeRV::new_row_var_use(0, TypeBound::Any); let inner_ft = Type::new_function(FuncValueType::new_endo(tv.clone())); - let ft_usz = Type::new_function(FuncValueType::new_endo(vec![tv.clone(), USIZE_T.into()])); + let ft_usz = Type::new_function(FuncValueType::new_endo(vec![tv.clone(), usize_t().into()])); let mut fb = FunctionBuilder::new( "id", PolyFuncType::new( @@ -673,14 +679,14 @@ fn row_variables() -> Result<(), Box> { // All the wires here are carrying higher-order Function values let [func_arg] = fb.input_wires_arr(); let id_usz = { - let bldr = fb.define_function("id_usz", Signature::new_endo(USIZE_T))?; + let bldr = fb.define_function("id_usz", Signature::new_endo(usize_t()))?; let vals = bldr.input_wires(); let inner_def = bldr.finish_with_outputs(vals)?; fb.load_func(inner_def.handle(), &[], &PRELUDE_REGISTRY)? }; let par = e.instantiate_extension_op( "parallel", - [tv.clone(), USIZE_T.into(), tv.clone(), USIZE_T.into()].map(seq1ty), + [tv.clone(), usize_t().into(), tv.clone(), usize_t().into()].map(seq1ty), &PRELUDE_REGISTRY, )?; let par_func = fb.add_dataflow_op(par, [func_arg, id_usz])?; @@ -726,10 +732,10 @@ fn test_polymorphic_call() -> Result<(), Box> { })?; fn utou(e: impl Into) -> Type { - Type::new_function(Signature::new_endo(USIZE_T).with_extension_delta(e.into())) + Type::new_function(Signature::new_endo(usize_t()).with_extension_delta(e.into())) } - let int_pair = Type::new_tuple(type_row![USIZE_T; 2]); + let int_pair = Type::new_tuple(vec![usize_t(); 2]); // Root DFG: applies a function int--PRELUDE-->int to each element of a pair of two ints let mut d = DFGBuilder::new(inout_sig( vec![utou(PRELUDE_ID), int_pair.clone()], @@ -750,15 +756,19 @@ fn test_polymorphic_call() -> Result<(), Box> { )?; let [func, tup] = f.input_wires_arr(); let mut c = f.conditional_builder( - (vec![type_row![USIZE_T; 2]], tup), + (vec![vec![usize_t(); 2].into()], tup), vec![], - type_row![USIZE_T;2], + vec![usize_t(); 2].into(), )?; let mut cc = c.case_builder(0)?; let [i1, i2] = cc.input_wires_arr(); let op = e.instantiate_extension_op( "eval", - vec![USIZE_T.into(), TypeArg::Extensions { es }, USIZE_T.into()], + vec![ + usize_t().into(), + TypeArg::Extensions { es }, + usize_t().into(), + ], &PRELUDE_REGISTRY, )?; let [f1] = cc.add_dataflow_op(op.clone(), [func, i1])?.outputs_arr(); @@ -800,10 +810,10 @@ fn test_polymorphic_load() -> Result<(), Box> { )?; let sig = Signature::new( vec![], - vec![Type::new_function(Signature::new_endo(vec![USIZE_T]))], + vec![Type::new_function(Signature::new_endo(vec![usize_t()]))], ); let mut f = m.define_function("main", sig)?; - let l = f.load_func(&id, &[USIZE_T.into()], &PRELUDE_REGISTRY)?; + let l = f.load_func(&id, &[usize_t().into()], &PRELUDE_REGISTRY)?; f.finish_with_outputs([l])?; let _ = m.finish_prelude_hugr()?; Ok(()) @@ -825,7 +835,7 @@ fn cfg_children_restrictions() { b.replace_op( copy, ops::CFG { - signature: Signature::new(type_row![BOOL_T], type_row![BOOL_T]), + signature: Signature::new(vec![bool_t()], vec![bool_t()]), }, ) .unwrap(); @@ -839,18 +849,18 @@ fn cfg_children_restrictions() { let block = b.add_node_with_parent( cfg, ops::DataflowBlock { - inputs: type_row![BOOL_T], + inputs: vec![bool_t()].into(), sum_rows: vec![type_row![]], - other_outputs: type_row![BOOL_T], + other_outputs: vec![bool_t()].into(), extension_delta: ExtensionSet::new(), }, ); let const_op: ops::Const = ops::Value::unit_sum(0, 1).unwrap().into(); let tag_type = Type::new_unit_sum(1); { - let input = b.add_node_with_parent(block, ops::Input::new(type_row![BOOL_T])); + let input = b.add_node_with_parent(block, ops::Input::new(vec![bool_t()])); let output = - b.add_node_with_parent(block, ops::Output::new(vec![tag_type.clone(), BOOL_T])); + b.add_node_with_parent(block, ops::Output::new(vec![tag_type.clone(), bool_t()])); let tag_def = b.add_node_with_parent(b.root(), const_op); let tag = b.add_node_with_parent(block, ops::LoadConstant { datatype: tag_type }); @@ -862,7 +872,7 @@ fn cfg_children_restrictions() { let exit = b.add_node_with_parent( cfg, ops::ExitBlock { - cfg_outputs: type_row![BOOL_T], + cfg_outputs: vec![bool_t()].into(), }, ); b.add_other_edge(block, exit); @@ -874,7 +884,7 @@ fn cfg_children_restrictions() { let exit2 = b.add_node_after( exit, ops::ExitBlock { - cfg_outputs: type_row![BOOL_T], + cfg_outputs: vec![bool_t()].into(), }, ); assert_matches!( @@ -888,16 +898,16 @@ fn cfg_children_restrictions() { b.replace_op( cfg, ops::CFG { - signature: Signature::new(type_row![QB_T], type_row![BOOL_T]), + signature: Signature::new(vec![qb_t()], vec![bool_t()]), }, ) .unwrap(); b.replace_op( block, ops::DataflowBlock { - inputs: type_row![QB_T], + inputs: vec![qb_t()].into(), sum_rows: vec![type_row![]], - other_outputs: type_row![QB_T], + other_outputs: vec![qb_t()].into(), extension_delta: ExtensionSet::new(), }, ) @@ -905,11 +915,11 @@ fn cfg_children_restrictions() { let mut block_children = b.hierarchy.children(block.pg_index()); let block_input = block_children.next().unwrap().into(); let block_output = block_children.next_back().unwrap().into(); - b.replace_op(block_input, ops::Input::new(type_row![QB_T])) + b.replace_op(block_input, ops::Input::new(vec![qb_t()])) .unwrap(); b.replace_op( block_output, - ops::Output::new(type_row![Type::new_unit_sum(1), QB_T]), + ops::Output::new(vec![Type::new_unit_sum(1), qb_t()]), ) .unwrap(); assert_matches!( @@ -926,14 +936,15 @@ fn cfg_children_restrictions() { fn cfg_connections() -> Result<(), Box> { use crate::builder::CFGBuilder; - let mut hugr = CFGBuilder::new(Signature::new_endo(USIZE_T))?; + let mut hugr = CFGBuilder::new(Signature::new_endo(usize_t()))?; let unary_pred = hugr.add_constant(Value::unary_unit_sum()); - let mut entry = hugr.simple_entry_builder_exts(type_row![USIZE_T], 1, ExtensionSet::new())?; + let mut entry = + hugr.simple_entry_builder_exts(vec![usize_t()].into(), 1, ExtensionSet::new())?; let p = entry.load_const(&unary_pred); let ins = entry.input_wires(); let entry = entry.finish_with_outputs(p, ins)?; - let mut middle = hugr.simple_block_builder(Signature::new_endo(USIZE_T), 1)?; + let mut middle = hugr.simple_block_builder(Signature::new_endo(usize_t()), 1)?; let p = middle.load_const(&unary_pred); let ins = middle.input_wires(); let middle = middle.finish_with_outputs(p, ins)?; @@ -1001,24 +1012,25 @@ mod extension_tests { ) { // Child graph adds extension "XB", but the parent (in all cases) // declares a different delta, causing a mismatch. - let parent = - parent_f(Signature::new_endo(USIZE_T).with_extension_delta(parent_extensions.clone())); + let parent = parent_f( + Signature::new_endo(usize_t()).with_extension_delta(parent_extensions.clone()), + ); let mut hugr = Hugr::new(parent); let input = hugr.add_node_with_parent( hugr.root(), ops::Input { - types: type_row![USIZE_T], + types: vec![usize_t()].into(), }, ); let output = hugr.add_node_with_parent( hugr.root(), ops::Output { - types: type_row![USIZE_T], + types: vec![usize_t()].into(), }, ); - let lift = hugr.add_node_with_parent(hugr.root(), Lift::new(type_row![USIZE_T], XB)); + let lift = hugr.add_node_with_parent(hugr.root(), Lift::new(vec![usize_t()].into(), XB)); hugr.connect(input, 0, lift, 0); hugr.connect(lift, 0, output, 0); @@ -1044,9 +1056,9 @@ mod extension_tests { #[case] success: bool, ) -> Result<(), BuildError> { let mut cfg = CFGBuilder::new( - Signature::new_endo(USIZE_T).with_extension_delta(parent_extensions.clone()), + Signature::new_endo(usize_t()).with_extension_delta(parent_extensions.clone()), )?; - let mut bb = cfg.simple_entry_builder_exts(USIZE_T.into(), 1, XB)?; + let mut bb = cfg.simple_entry_builder_exts(usize_t().into(), 1, XB)?; let pred = bb.add_load_value(Value::unary_unit_sum()); let inputs = bb.input_wires(); let blk = bb.finish_with_outputs(pred, inputs)?; @@ -1082,8 +1094,8 @@ mod extension_tests { // declares a different delta, in same cases causing a mismatch. let parent = ops::Conditional { sum_rows: vec![type_row![], type_row![]], - other_inputs: type_row![USIZE_T], - outputs: type_row![USIZE_T], + other_inputs: vec![usize_t()].into(), + outputs: vec![usize_t()].into(), extension_delta: parent_extensions.clone(), }; let mut hugr = Hugr::new(parent); @@ -1098,27 +1110,27 @@ mod extension_tests { let case = hugr.add_node_with_parent( hugr.root(), ops::Case { - signature: Signature::new_endo(USIZE_T).with_extension_delta(case_exts), + signature: Signature::new_endo(usize_t()).with_extension_delta(case_exts), }, ); let input = hugr.add_node_with_parent( case, ops::Input { - types: type_row![USIZE_T], + types: vec![usize_t()].into(), }, ); let output = hugr.add_node_with_parent( case, ops::Output { - types: type_row![USIZE_T], + types: vec![usize_t()].into(), }, ); let res = match case_ext { None => input, Some(new_ext) => { let lift = - hugr.add_node_with_parent(case, Lift::new(type_row![USIZE_T], new_ext)); + hugr.add_node_with_parent(case, Lift::new(vec![usize_t()].into(), new_ext)); hugr.connect(input, 0, lift, 0); lift } @@ -1151,8 +1163,8 @@ mod extension_tests { parent_exts_success: (ExtensionSet, bool), ) -> Result<(), BuildError> { let (parent_extensions, success) = parent_exts_success; - let mut dfg = dfg_fn(USIZE_T, parent_extensions.clone()); - let lift = dfg.add_dataflow_op(Lift::new(USIZE_T.into(), XB), dfg.input_wires())?; + let mut dfg = dfg_fn(usize_t(), parent_extensions.clone()); + let lift = dfg.add_dataflow_op(Lift::new(usize_t().into(), XB), dfg.input_wires())?; let pred = make_pred(&mut dfg, lift.outputs())?; let root = dfg.hugr().root(); let res = dfg.finish_prelude_hugr_with_outputs([pred]); diff --git a/hugr-core/src/hugr/views/descendants.rs b/hugr-core/src/hugr/views/descendants.rs index 64082eb7e..c1aa7da1f 100644 --- a/hugr-core/src/hugr/views/descendants.rs +++ b/hugr-core/src/hugr/views/descendants.rs @@ -175,20 +175,17 @@ where pub(super) mod test { use rstest::rstest; + use crate::extension::prelude::{qb_t, usize_t}; use crate::extension::PRELUDE_REGISTRY; use crate::IncomingPort; use crate::{ builder::{Container, Dataflow, DataflowSubContainer, HugrBuilder, ModuleBuilder}, - type_row, - types::{Signature, Type}, + types::Signature, utils::test_quantum_extension::{h_gate, EXTENSION_ID}, }; use super::*; - const NAT: Type = crate::extension::prelude::USIZE_T; - const QB: Type = crate::extension::prelude::QB_T; - /// Make a module hugr with a fn definition containing an inner dfg node. /// /// Returns the hugr, the fn node id, and the nested dgf node id. @@ -199,7 +196,7 @@ pub(super) mod test { let (f_id, inner_id) = { let mut func_builder = module_builder.define_function( "main", - Signature::new_endo(type_row![NAT, QB]).with_extension_delta(EXTENSION_ID), + Signature::new_endo(vec![usize_t(), qb_t()]).with_extension_delta(EXTENSION_ID), )?; let [int, qb] = func_builder.input_wires_arr(); @@ -208,7 +205,7 @@ pub(super) mod test { let inner_id = { let inner_builder = func_builder - .dfg_builder(Signature::new(type_row![NAT], type_row![NAT]), [int])?; + .dfg_builder(Signature::new(vec![usize_t()], vec![usize_t()]), [int])?; let w = inner_builder.input_wires(); inner_builder.finish_with_outputs(w) }?; @@ -237,7 +234,7 @@ pub(super) mod test { assert_eq!( region.poly_func_type(), Some( - Signature::new_endo(type_row![NAT, QB]) + Signature::new_endo(vec![usize_t(), qb_t()]) .with_extension_delta(EXTENSION_ID) .into() ) @@ -246,7 +243,7 @@ pub(super) mod test { let inner_region: DescendantsGraph = DescendantsGraph::try_new(&hugr, inner)?; assert_eq!( inner_region.inner_function_type(), - Some(Signature::new(type_row![NAT], type_row![NAT])) + Some(Signature::new(vec![usize_t()], vec![usize_t()])) ); assert_eq!(inner_region.node_count(), 3); assert_eq!(inner_region.edge_count(), 2); diff --git a/hugr-core/src/hugr/views/sibling.rs b/hugr-core/src/hugr/views/sibling.rs index 45ed1f759..6fb4246d0 100644 --- a/hugr-core/src/hugr/views/sibling.rs +++ b/hugr-core/src/hugr/views/sibling.rs @@ -336,16 +336,14 @@ mod test { use crate::builder::test::simple_dfg_hugr; use crate::builder::{Container, Dataflow, DataflowSubContainer, HugrBuilder, ModuleBuilder}; + use crate::extension::prelude::{qb_t, usize_t}; use crate::extension::PRELUDE_REGISTRY; use crate::ops::handle::{CfgID, DataflowParentID, DfgID, FuncID}; use crate::ops::{dataflow::IOTrait, Input, OpTag, Output}; use crate::ops::{OpTrait, OpType}; - use crate::types::{Signature, Type}; + use crate::types::Signature; use crate::utils::test_quantum_extension::EXTENSION_ID; - use crate::{type_row, IncomingPort}; - - const NAT: Type = crate::extension::prelude::USIZE_T; - const QB: Type = crate::extension::prelude::QB_T; + use crate::IncomingPort; use super::super::descendants::test::make_module_hgr; use super::*; @@ -372,7 +370,7 @@ mod test { assert_eq!( region.poly_func_type(), Some( - Signature::new_endo(type_row![NAT, QB]) + Signature::new_endo(vec![usize_t(), qb_t()]) .with_extension_delta(EXTENSION_ID) .into() ) @@ -380,7 +378,7 @@ mod test { assert_eq!( inner_region.inner_function_type(), - Some(Signature::new(type_row![NAT], type_row![NAT])) + Some(Signature::new(vec![usize_t()], vec![usize_t()])) ); assert_eq!(inner_region.node_count(), 3); assert_eq!(inner_region.edge_count(), 1); @@ -453,7 +451,7 @@ mod test { #[test] fn nested_flat() -> Result<(), Box> { let mut module_builder = ModuleBuilder::new(); - let fty = Signature::new(type_row![NAT], type_row![NAT]); + let fty = Signature::new(vec![usize_t()], vec![usize_t()]); let mut fbuild = module_builder.define_function("main", fty.clone())?; let dfg = fbuild.dfg_builder(fty, fbuild.input_wires())?; let ins = dfg.input_wires(); @@ -472,8 +470,8 @@ mod test { // Both ways work: let just_io = vec![ - Input::new(type_row![NAT]).into(), - Output::new(type_row![NAT]).into(), + Input::new(vec![usize_t()]).into(), + Output::new(vec![usize_t()]).into(), ]; for d in [dfg_view, nested_dfg_view] { assert_eq!( diff --git a/hugr-core/src/hugr/views/sibling_subgraph.rs b/hugr-core/src/hugr/views/sibling_subgraph.rs index fad4d835c..de82ae591 100644 --- a/hugr-core/src/hugr/views/sibling_subgraph.rs +++ b/hugr-core/src/hugr/views/sibling_subgraph.rs @@ -796,13 +796,12 @@ mod tests { ModuleBuilder, }, extension::{ - prelude::{BOOL_T, QB_T}, + prelude::{bool_t, qb_t}, EMPTY_REG, }, hugr::views::{HierarchyView, SiblingGraph}, ops::handle::{DfgID, FuncID, NodeHandle}, std_extensions::logic::test::and_op, - type_row, }; use super::*; @@ -837,7 +836,7 @@ mod tests { let mut mod_builder = ModuleBuilder::new(); let func = mod_builder.declare( "test", - Signature::new_endo(type_row![QB_T, QB_T, QB_T]) + Signature::new_endo(vec![qb_t(), qb_t(), qb_t()]) .with_extension_delta(ExtensionSet::from_iter([ test_quantum_extension::EXTENSION_ID, float_types::EXTENSION_ID, @@ -870,7 +869,7 @@ mod tests { let mut mod_builder = ModuleBuilder::new(); let func = mod_builder.declare( "test", - Signature::new_endo(type_row![BOOL_T]) + Signature::new_endo(vec![bool_t()]) .with_extension_delta(logic::EXTENSION_ID) .into(), )?; @@ -892,7 +891,7 @@ mod tests { let mut mod_builder = ModuleBuilder::new(); let func = mod_builder.declare( "test", - Signature::new(BOOL_T, type_row![BOOL_T, BOOL_T]) + Signature::new(bool_t(), vec![bool_t(), bool_t()]) .with_extension_delta(logic::EXTENSION_ID) .into(), )?; @@ -914,7 +913,7 @@ mod tests { let mut mod_builder = ModuleBuilder::new(); let func = mod_builder.declare( "test", - Signature::new_endo(BOOL_T) + Signature::new_endo(bool_t()) .with_extension_delta(logic::EXTENSION_ID) .into(), )?; @@ -956,7 +955,7 @@ mod tests { let empty_dfg = { let builder = - DFGBuilder::new(Signature::new_endo(type_row![QB_T, QB_T, QB_T])).unwrap(); + DFGBuilder::new(Signature::new_endo(vec![qb_t(), qb_t(), qb_t()])).unwrap(); let inputs = builder.input_wires(); builder.finish_prelude_hugr_with_outputs(inputs).unwrap() }; @@ -979,7 +978,7 @@ mod tests { let sub = SiblingSubgraph::try_new_dataflow_subgraph(&func)?; assert_eq!( sub.signature(&func), - Signature::new_endo(type_row![QB_T, QB_T, QB_T]).with_extension_delta( + Signature::new_endo(vec![qb_t(), qb_t(), qb_t()]).with_extension_delta( ExtensionSet::from_iter([ test_quantum_extension::EXTENSION_ID, float_types::EXTENSION_ID, @@ -996,7 +995,7 @@ mod tests { let sub = SiblingSubgraph::from_sibling_graph(&func)?; let empty_dfg = { - let builder = DFGBuilder::new(Signature::new_endo(type_row![QB_T])).unwrap(); + let builder = DFGBuilder::new(Signature::new_endo(vec![qb_t()])).unwrap(); let inputs = builder.input_wires(); builder.finish_prelude_hugr_with_outputs(inputs).unwrap() }; @@ -1157,8 +1156,8 @@ mod tests { #[test] fn edge_both_output_and_copy() { // https://github.com/CQCL/hugr/issues/518 - let one_bit = type_row![BOOL_T]; - let two_bit = type_row![BOOL_T, BOOL_T]; + let one_bit = vec![bool_t()]; + let two_bit = vec![bool_t(), bool_t()]; let mut builder = DFGBuilder::new(inout_sig(one_bit.clone(), two_bit.clone())).unwrap(); let inw = builder.input_wires().exactly_one().unwrap(); diff --git a/hugr-core/src/hugr/views/tests.rs b/hugr-core/src/hugr/views/tests.rs index c958c8b9f..a703ece54 100644 --- a/hugr-core/src/hugr/views/tests.rs +++ b/hugr-core/src/hugr/views/tests.rs @@ -5,7 +5,7 @@ use crate::{ builder::{ endo_sig, inout_sig, BuildError, BuildHandle, Container, DFGBuilder, Dataflow, DataflowHugr, }, - extension::prelude::QB_T, + extension::prelude::qb_t, ops::{ handle::{DataflowOpID, NodeHandle}, Value, @@ -22,7 +22,7 @@ use crate::{ /// Returns the Hugr and the two CX node ids. #[fixture] pub(crate) fn sample_hugr() -> (Hugr, BuildHandle, BuildHandle) { - let mut dfg = DFGBuilder::new(endo_sig(type_row![QB_T, QB_T])).unwrap(); + let mut dfg = DFGBuilder::new(endo_sig(vec![qb_t(), qb_t()])).unwrap(); let [q1, q2] = dfg.input_wires_arr(); @@ -130,13 +130,13 @@ fn all_ports(sample_hugr: (Hugr, BuildHandle, BuildHandle>().join(", "))] + Extension { + /// The missing extension. + missing_ext: ExtensionId, + /// The available extensions in the registry. + available: Vec, + }, /// The model is not well-formed. #[error("validate error: {0}")] Model(#[from] model::ModelError), @@ -1093,6 +1104,14 @@ impl<'a> Context<'a> { let name = self.get_global_name(*name)?; let (extension, id) = self.import_custom_name(name)?; + let extension_ref = + self.extensions.get(&extension.to_string()).ok_or_else(|| { + ImportError::Extension { + missing_ext: extension.clone(), + available: self.extensions.ids().cloned().collect(), + } + })?; + Ok(TypeBase::new_extension(CustomType::new( id, args, @@ -1100,6 +1119,7 @@ impl<'a> Context<'a> { // As part of the migration from `TypeBound`s to constraints, we pretend that all // `TypeBound`s are copyable. TypeBound::Copyable, + &Arc::downgrade(extension_ref), ))) } diff --git a/hugr-core/src/ops/constant.rs b/hugr-core/src/ops/constant.rs index 3522c61b3..f79f05d12 100644 --- a/hugr-core/src/ops/constant.rs +++ b/hugr-core/src/ops/constant.rs @@ -243,23 +243,23 @@ pub enum Value { /// use serde::{Serialize,Deserialize}; /// use hugr::{ /// types::Type,ops::constant::{OpaqueValue, ValueName, CustomConst, CustomSerialized}, -/// extension::{ExtensionSet, prelude::{USIZE_T, ConstUsize}}, +/// extension::{ExtensionSet, prelude::{usize_t, ConstUsize}}, /// std_extensions::arithmetic::int_types}; /// use serde_json::json; /// /// let expected_json = json!({ /// "extensions": ["prelude"], -/// "typ": USIZE_T, +/// "typ": usize_t(), /// "value": {'c': "ConstUsize", 'v': 1} /// }); /// let ev = OpaqueValue::new(ConstUsize::new(1)); /// assert_eq!(&serde_json::to_value(&ev).unwrap(), &expected_json); /// assert_eq!(ev, serde_json::from_value(expected_json).unwrap()); /// -/// let ev = OpaqueValue::new(CustomSerialized::new(USIZE_T.clone(), serde_json::Value::Null, ExtensionSet::default())); +/// let ev = OpaqueValue::new(CustomSerialized::new(usize_t().clone(), serde_json::Value::Null, ExtensionSet::default())); /// let expected_json = json!({ /// "extensions": [], -/// "typ": USIZE_T, +/// "typ": usize_t(), /// "value": null /// }); /// @@ -560,18 +560,20 @@ pub type ValueNameRef = str; #[cfg(test)] mod test { use std::collections::HashSet; + use std::sync::{Arc, Weak}; use super::Value; use crate::builder::inout_sig; use crate::builder::test::simple_dfg_hugr; + use crate::extension::prelude::{bool_t, usize_custom_t}; use crate::std_extensions::arithmetic::int_types::ConstInt; use crate::{ builder::{BuildError, DFGBuilder, Dataflow, DataflowHugr}, extension::{ - prelude::{ConstUsize, USIZE_CUSTOM_T, USIZE_T}, + prelude::{usize_t, ConstUsize}, ExtensionId, ExtensionRegistry, PRELUDE, }, - std_extensions::arithmetic::float_types::{self, ConstF64, FLOAT64_TYPE}, + std_extensions::arithmetic::float_types::{self, float64_type, ConstF64}, type_row, types::type_param::TypeArg, types::{Type, TypeBound, TypeRow}, @@ -604,7 +606,7 @@ mod test { } } - /// A [`CustomSerialized`] encoding a [`FLOAT64_TYPE`] float constant used in testing. + /// A [`CustomSerialized`] encoding a [`float64_type()`] float constant used in testing. pub(crate) fn serialized_float(f: f64) -> Value { CustomSerialized::try_from_custom_const(ConstF64::new(f)) .unwrap() @@ -619,17 +621,18 @@ mod test { #[test] fn test_sum() -> Result<(), BuildError> { use crate::builder::Container; - let pred_rows = vec![type_row![USIZE_T, FLOAT64_TYPE], Type::EMPTY_TYPEROW]; + let pred_rows = vec![vec![usize_t(), float64_type()].into(), Type::EMPTY_TYPEROW]; let pred_ty = SumType::new(pred_rows.clone()); let mut b = DFGBuilder::new(inout_sig( type_row![], TypeRow::from(vec![pred_ty.clone().into()]), ))?; + let usize_custom_t = usize_custom_t(&Arc::downgrade(&PRELUDE)); let c = b.add_constant(Value::sum( 0, [ - CustomTestValue(USIZE_CUSTOM_T).into(), + CustomTestValue(usize_custom_t.clone()).into(), ConstF64::new(5.1).into(), ], pred_ty.clone(), @@ -650,7 +653,7 @@ mod test { #[test] fn test_bad_sum() { - let pred_ty = SumType::new([type_row![USIZE_T, FLOAT64_TYPE], type_row![]]); + let pred_ty = SumType::new([vec![usize_t(), float64_type()].into(), type_row![]]); let good_sum = const_usize(); println!("{}", serde_json::to_string_pretty(&good_sum).unwrap()); @@ -686,7 +689,7 @@ mod test { index: 1, expected, found, - })) if expected == FLOAT64_TYPE && found == const_usize() + })) if expected == float64_type() && found == const_usize() ); } @@ -694,9 +697,7 @@ mod test { fn function_value(simple_dfg_hugr: Hugr) { let v = Value::function(simple_dfg_hugr).unwrap(); - let correct_type = Type::new_function(Signature::new_endo(type_row![ - crate::extension::prelude::BOOL_T - ])); + let correct_type = Type::new_function(Signature::new_endo(vec![bool_t()])); assert_eq!(v.get_type(), correct_type); assert!(v.name().starts_with("const:function:")) @@ -714,9 +715,9 @@ mod test { #[rstest] #[case(Value::unit(), Type::UNIT, "const:seq:{}")] - #[case(const_usize(), USIZE_T, "const:custom:ConstUsize(")] - #[case(serialized_float(17.4), FLOAT64_TYPE, "const:custom:json:Object")] - #[case(const_tuple(), Type::new_tuple(type_row![USIZE_T, FLOAT64_TYPE]), "const:seq:{")] + #[case(const_usize(), usize_t(), "const:custom:ConstUsize(")] + #[case(serialized_float(17.4), float64_type(), "const:custom:json:Object")] + #[case(const_tuple(), Type::new_tuple(vec![usize_t(), float64_type()]), "const:seq:{")] fn const_type( #[case] const_value: Value, #[case] expected_type: Type, @@ -749,6 +750,8 @@ mod test { vec![TypeArg::BoundedNat { n: 8 }], ex_id.clone(), TypeBound::Copyable, + // Dummy extension reference. + &Weak::default(), ); let json_const: Value = CustomSerialized::new(typ_int.clone(), 6.into(), ex_id.clone()).into(); @@ -756,7 +759,13 @@ mod test { assert_matches!(classic_t.least_upper_bound(), TypeBound::Copyable); assert_eq!(json_const.get_type(), classic_t); - let typ_qb = CustomType::new("my_type", vec![], ex_id, TypeBound::Copyable); + let typ_qb = CustomType::new( + "my_type", + vec![], + ex_id, + TypeBound::Copyable, + &Weak::default(), + ); let t = Type::new_extension(typ_qb.clone()); assert_ne!(json_const.get_type(), t); } @@ -937,7 +946,10 @@ mod test { Value::sum( 1, [Value::true_val()], - SumType::new([vec![Type::UNIT], vec![Value::true_val().get_type()]]), + SumType::new([ + type_row![Type::UNIT], + vec![Value::true_val().get_type()].into() + ]), ) .unwrap() ]) diff --git a/hugr-core/src/ops/constant/custom.rs b/hugr-core/src/ops/constant/custom.rs index a95b4b9ba..b6755d5c6 100644 --- a/hugr-core/src/ops/constant/custom.rs +++ b/hugr-core/src/ops/constant/custom.rs @@ -62,7 +62,7 @@ pub trait CustomConst: /// (a set to allow, say, a [List] of [USize]) /// /// [List]: crate::std_extensions::collections::LIST_TYPENAME - /// [USize]: crate::extension::prelude::USIZE_T + /// [USize]: crate::extension::prelude::usize_t fn extension_reqs(&self) -> ExtensionSet; /// Check the value. @@ -360,7 +360,7 @@ mod test { use rstest::rstest; use crate::{ - extension::prelude::{ConstUsize, USIZE_T}, + extension::prelude::{usize_t, ConstUsize}, ops::{constant::custom::serialize_custom_const, Value}, std_extensions::collections::ListValue, }; @@ -386,7 +386,7 @@ mod test { fn scce_list() -> SerializeCustomConstExample { let cc = ListValue::new( - USIZE_T, + usize_t(), [ConstUsize::new(1), ConstUsize::new(2)] .into_iter() .map(Value::extension), diff --git a/hugr-core/src/ops/custom.rs b/hugr-core/src/ops/custom.rs index d7f1c2c57..fb875c158 100644 --- a/hugr-core/src/ops/custom.rs +++ b/hugr-core/src/ops/custom.rs @@ -354,7 +354,7 @@ mod test { use crate::std_extensions::arithmetic::conversions::{self, CONVERT_OPS_REGISTRY}; use crate::{ extension::{ - prelude::{BOOL_T, QB_T, USIZE_T}, + prelude::{bool_t, qb_t, usize_t}, SignatureFunc, }, std_extensions::arithmetic::int_types::INT_TYPES, @@ -366,17 +366,17 @@ mod test { #[test] fn new_opaque_op() { - let sig = Signature::new_endo(vec![QB_T]); + let sig = Signature::new_endo(vec![qb_t()]); let op = OpaqueOp::new( "res".try_into().unwrap(), "op", "desc".into(), - vec![TypeArg::Type { ty: USIZE_T }], + vec![TypeArg::Type { ty: usize_t() }], sig.clone(), ); assert_eq!(op.name(), "res.op"); assert_eq!(DataflowOpTrait::description(&op), "desc"); - assert_eq!(op.args(), &[TypeArg::Type { ty: USIZE_T }]); + assert_eq!(op.args(), &[TypeArg::Type { ty: usize_t() }]); assert_eq!( op.signature(), sig.with_extension_delta(op.extension().clone()) @@ -392,7 +392,7 @@ mod test { "itobool", "description".into(), vec![], - Signature::new(i0.clone(), BOOL_T), + Signature::new(i0.clone(), bool_t()), ); let resolved = super::resolve_opaque_op(Node::from(portgraph::NodeIndex::new(1)), &opaque, registry) @@ -404,7 +404,7 @@ mod test { fn resolve_missing() { let val_name = "missing_val"; let comp_name = "missing_comp"; - let endo_sig = Signature::new_endo(BOOL_T); + let endo_sig = Signature::new_endo(bool_t()); let ext = Extension::new_test_arc("ext".try_into().unwrap(), |ext, extension_ref| { ext.add_op( diff --git a/hugr-core/src/ops/dataflow.rs b/hugr-core/src/ops/dataflow.rs index 364429784..ed9a9e118 100644 --- a/hugr-core/src/ops/dataflow.rs +++ b/hugr-core/src/ops/dataflow.rs @@ -221,9 +221,9 @@ impl Call { /// # use hugr::ops::dataflow::Call; /// # use hugr::ops::OpType; /// # use hugr::types::Signature; - /// # use hugr::extension::prelude::QB_T; + /// # use hugr::extension::prelude::qb_t; /// # use hugr::extension::PRELUDE_REGISTRY; - /// let signature = Signature::new(vec![QB_T, QB_T], vec![QB_T, QB_T]); + /// let signature = Signature::new(vec![qb_t(), qb_t()], vec![qb_t(), qb_t()]); /// let call = Call::try_new(signature.into(), &[], &PRELUDE_REGISTRY).unwrap(); /// let op = OpType::Call(call.clone()); /// assert_eq!(op.static_input_port(), Some(call.called_function_port())); diff --git a/hugr-core/src/ops/validate.rs b/hugr-core/src/ops/validate.rs index ce67bb9a0..16eed59e6 100644 --- a/hugr-core/src/ops/validate.rs +++ b/hugr-core/src/ops/validate.rs @@ -351,21 +351,21 @@ fn validate_cfg_edge(edge: ChildrenEdgeData) -> Result<(), EdgeValidationError> #[cfg(test)] mod test { - use crate::extension::prelude::{Noop, USIZE_T}; + use crate::extension::prelude::{usize_t, Noop}; + use crate::ops; use crate::ops::dataflow::IOTrait; - use crate::{ops, type_row}; use cool_asserts::assert_matches; use super::*; #[test] fn test_validate_io_nodes() { - let in_types: TypeRow = type_row![USIZE_T]; - let out_types: TypeRow = type_row![USIZE_T, USIZE_T]; + let in_types: TypeRow = vec![usize_t()].into(); + let out_types: TypeRow = vec![usize_t(), usize_t()].into(); let input_node: OpType = ops::Input::new(in_types.clone()).into(); let output_node = ops::Output::new(out_types.clone()).into(); - let leaf_node = Noop(USIZE_T).into(); + let leaf_node = Noop(usize_t()).into(); // Well-formed dataflow sibling nodes. Check the input and output node signatures. let children = vec![ diff --git a/hugr-core/src/std_extensions/arithmetic/conversions.rs b/hugr-core/src/std_extensions/arithmetic/conversions.rs index 4d3263f09..b8b2771c2 100644 --- a/hugr-core/src/std_extensions/arithmetic/conversions.rs +++ b/hugr-core/src/std_extensions/arithmetic/conversions.rs @@ -1,28 +1,24 @@ //! Conversions between integer and floating-point values. -use std::sync::Arc; +use std::sync::{Arc, Weak}; use strum_macros::{EnumIter, EnumString, IntoStaticStr}; -use crate::extension::prelude::{BOOL_T, STRING_TYPE, USIZE_T}; +use crate::extension::prelude::sum_with_error; +use crate::extension::prelude::{bool_t, string_type, usize_t}; use crate::extension::simple_op::{HasConcrete, HasDef}; +use crate::extension::simple_op::{MakeExtensionOp, MakeOpDef, MakeRegisteredOp, OpLoadError}; +use crate::extension::{ + ExtensionId, ExtensionRegistry, ExtensionSet, OpDef, SignatureError, SignatureFunc, PRELUDE, +}; use crate::ops::OpName; +use crate::ops::{custom::ExtensionOp, NamedOp}; use crate::std_extensions::arithmetic::int_ops::int_polytype; use crate::std_extensions::arithmetic::int_types::int_type; -use crate::{ - extension::{ - prelude::sum_with_error, - simple_op::{MakeExtensionOp, MakeOpDef, MakeRegisteredOp, OpLoadError}, - ExtensionId, ExtensionRegistry, ExtensionSet, OpDef, SignatureError, SignatureFunc, - PRELUDE, - }, - ops::{custom::ExtensionOp, NamedOp}, - type_row, - types::{TypeArg, TypeRV}, - Extension, -}; +use crate::types::{TypeArg, TypeRV}; +use crate::Extension; -use super::float_types::FLOAT64_TYPE; +use super::float_types::float64_type; use super::int_types::{get_log_width, int_tv}; use lazy_static::lazy_static; mod const_fold; @@ -57,20 +53,24 @@ impl MakeOpDef for ConvertOpDef { EXTENSION_ID.to_owned() } - fn signature(&self) -> SignatureFunc { + fn extension_ref(&self) -> Weak { + Arc::downgrade(&EXTENSION) + } + + fn init_signature(&self, _extension_ref: &Weak) -> SignatureFunc { use ConvertOpDef::*; match self { trunc_s | trunc_u => int_polytype( 1, - type_row![FLOAT64_TYPE], + vec![float64_type()], TypeRV::from(sum_with_error(int_tv(0))), ), - convert_s | convert_u => int_polytype(1, vec![int_tv(0)], type_row![FLOAT64_TYPE]), - itobool => int_polytype(0, vec![int_type(0)], vec![BOOL_T]), - ifrombool => int_polytype(0, vec![BOOL_T], vec![int_type(0)]), - itostring_u | itostring_s => int_polytype(1, vec![int_tv(0)], vec![STRING_TYPE]), - itousize => int_polytype(0, vec![int_type(6)], vec![USIZE_T]), - ifromusize => int_polytype(0, vec![USIZE_T], vec![int_type(6)]), + convert_s | convert_u => int_polytype(1, vec![int_tv(0)], vec![float64_type()]), + itobool => int_polytype(0, vec![int_type(0)], vec![bool_t()]), + ifrombool => int_polytype(0, vec![bool_t()], vec![int_type(0)]), + itostring_u | itostring_s => int_polytype(1, vec![int_tv(0)], vec![string_type()]), + itousize => int_polytype(0, vec![int_type(6)], vec![usize_t()]), + ifromusize => int_polytype(0, vec![usize_t()], vec![int_type(6)]), } .into() } diff --git a/hugr-core/src/std_extensions/arithmetic/conversions/const_fold.rs b/hugr-core/src/std_extensions/arithmetic/conversions/const_fold.rs index e9c736858..8ef7bb63d 100644 --- a/hugr-core/src/std_extensions/arithmetic/conversions/const_fold.rs +++ b/hugr-core/src/std_extensions/arithmetic/conversions/const_fold.rs @@ -4,7 +4,7 @@ use crate::ops::Value; use crate::std_extensions::arithmetic::int_types::INT_TYPES; use crate::{ extension::{ - prelude::{const_ok, ConstError, ERROR_TYPE}, + prelude::{const_ok, error_type, ConstError}, ConstFold, ConstFoldResult, OpDef, }, ops, @@ -59,7 +59,7 @@ fn fold_trunc( } else { let cv = convert(f, log_width); if let Ok(cv) = cv { - const_ok(cv, ERROR_TYPE) + const_ok(cv, error_type()) } else { err_value() } diff --git a/hugr-core/src/std_extensions/arithmetic/float_ops.rs b/hugr-core/src/std_extensions/arithmetic/float_ops.rs index 9be2c6786..dad35d3c7 100644 --- a/hugr-core/src/std_extensions/arithmetic/float_ops.rs +++ b/hugr-core/src/std_extensions/arithmetic/float_ops.rs @@ -1,17 +1,16 @@ //! Basic floating-point operations. -use std::sync::Arc; +use std::sync::{Arc, Weak}; use strum_macros::{EnumIter, EnumString, IntoStaticStr}; -use super::float_types::FLOAT64_TYPE; +use super::float_types::float64_type; use crate::{ extension::{ - prelude::{BOOL_T, STRING_TYPE}, + prelude::{bool_t, string_type}, simple_op::{MakeOpDef, MakeRegisteredOp, OpLoadError}, ExtensionId, ExtensionRegistry, ExtensionSet, OpDef, SignatureFunc, PRELUDE, }, - type_row, types::Signature, Extension, }; @@ -57,18 +56,22 @@ impl MakeOpDef for FloatOps { EXTENSION_ID.to_owned() } - fn signature(&self) -> SignatureFunc { + fn extension_ref(&self) -> Weak { + Arc::downgrade(&EXTENSION) + } + + fn init_signature(&self, _extension_ref: &Weak) -> SignatureFunc { use FloatOps::*; match self { feq | fne | flt | fgt | fle | fge => { - Signature::new(type_row![FLOAT64_TYPE; 2], type_row![BOOL_T]) + Signature::new(vec![float64_type(); 2], vec![bool_t()]) } fmax | fmin | fadd | fsub | fmul | fdiv | fpow => { - Signature::new(type_row![FLOAT64_TYPE; 2], type_row![FLOAT64_TYPE]) + Signature::new(vec![float64_type(); 2], vec![float64_type()]) } - fneg | fabs | ffloor | fceil | fround => Signature::new_endo(type_row![FLOAT64_TYPE]), - ftostring => Signature::new(type_row![FLOAT64_TYPE], STRING_TYPE), + fneg | fabs | ffloor | fceil | fround => Signature::new_endo(vec![float64_type()]), + ftostring => Signature::new(vec![float64_type()], string_type()), } .into() } diff --git a/hugr-core/src/std_extensions/arithmetic/float_types.rs b/hugr-core/src/std_extensions/arithmetic/float_types.rs index 0af5f8728..304f44899 100644 --- a/hugr-core/src/std_extensions/arithmetic/float_types.rs +++ b/hugr-core/src/std_extensions/arithmetic/float_types.rs @@ -1,6 +1,6 @@ //! Basic floating-point types -use std::sync::Arc; +use std::sync::{Arc, Weak}; use crate::ops::constant::{TryHash, ValueName}; use crate::types::TypeName; @@ -18,14 +18,23 @@ pub const EXTENSION_ID: ExtensionId = ExtensionId::new_unchecked("arithmetic.flo pub const VERSION: semver::Version = semver::Version::new(0, 1, 0); /// Identifier for the 64-bit IEEE 754-2019 floating-point type. -const FLOAT_TYPE_ID: TypeName = TypeName::new_inline("float64"); +pub const FLOAT_TYPE_ID: TypeName = TypeName::new_inline("float64"); /// 64-bit IEEE 754-2019 floating-point type (as [CustomType]) -pub const FLOAT64_CUSTOM_TYPE: CustomType = - CustomType::new_simple(FLOAT_TYPE_ID, EXTENSION_ID, TypeBound::Copyable); +pub fn float64_custom_type(extension_ref: &Weak) -> CustomType { + CustomType::new( + FLOAT_TYPE_ID, + vec![], + EXTENSION_ID, + TypeBound::Copyable, + extension_ref, + ) +} /// 64-bit IEEE 754-2019 floating-point type (as [Type]) -pub const FLOAT64_TYPE: Type = Type::new_extension(FLOAT64_CUSTOM_TYPE); +pub fn float64_type() -> Type { + float64_custom_type(&Arc::downgrade(&EXTENSION)).into() +} #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] /// A floating-point value. @@ -67,7 +76,7 @@ impl CustomConst for ConstF64 { } fn get_type(&self) -> Type { - FLOAT64_TYPE + float64_type() } fn equal_consts(&self, _: &dyn CustomConst) -> bool { diff --git a/hugr-core/src/std_extensions/arithmetic/int_ops.rs b/hugr-core/src/std_extensions/arithmetic/int_ops.rs index 132a01f35..4f6332767 100644 --- a/hugr-core/src/std_extensions/arithmetic/int_ops.rs +++ b/hugr-core/src/std_extensions/arithmetic/int_ops.rs @@ -1,9 +1,9 @@ //! Basic integer operations. -use std::sync::Arc; +use std::sync::{Arc, Weak}; use super::int_types::{get_log_width, int_tv, LOG_WIDTH_TYPE_PARAM}; -use crate::extension::prelude::{sum_with_error, BOOL_T}; +use crate::extension::prelude::{bool_t, sum_with_error}; use crate::extension::simple_op::{ HasConcrete, HasDef, MakeExtensionOp, MakeOpDef, MakeRegisteredOp, OpLoadError, }; @@ -12,7 +12,6 @@ use crate::extension::{ }; use crate::ops::custom::ExtensionOp; use crate::ops::{NamedOp, OpName}; -use crate::type_row; use crate::types::{FuncValueType, PolyFuncTypeRV, TypeRowRV}; use crate::utils::collect_array; @@ -111,7 +110,11 @@ impl MakeOpDef for IntOpDef { EXTENSION_ID.to_owned() } - fn signature(&self) -> SignatureFunc { + fn extension_ref(&self) -> Weak { + Arc::downgrade(&EXTENSION) + } + + fn init_signature(&self, _extension_ref: &Weak) -> SignatureFunc { use IntOpDef::*; let tv0 = int_tv(0); match self { @@ -126,7 +129,7 @@ impl MakeOpDef for IntOpDef { ) .into(), ieq | ine | ilt_u | ilt_s | igt_u | igt_s | ile_u | ile_s | ige_u | ige_s => { - int_polytype(1, vec![tv0; 2], type_row![BOOL_T]).into() + int_polytype(1, vec![tv0; 2], vec![bool_t()]).into() } imax_u | imax_s | imin_u | imin_s | iadd | isub | imul | iand | ior | ixor | ipow => { ibinop_sig().into() diff --git a/hugr-core/src/std_extensions/arithmetic/int_types.rs b/hugr-core/src/std_extensions/arithmetic/int_types.rs index 82f1c27ae..db52c6576 100644 --- a/hugr-core/src/std_extensions/arithmetic/int_types.rs +++ b/hugr-core/src/std_extensions/arithmetic/int_types.rs @@ -1,7 +1,7 @@ //! Basic integer types use std::num::NonZeroU64; -use std::sync::Arc; +use std::sync::{Arc, Weak}; use crate::ops::constant::ValueName; use crate::types::TypeName; @@ -26,12 +26,16 @@ pub const INT_TYPE_ID: TypeName = TypeName::new_inline("int"); /// Integer type of a given bit width (specified by the TypeArg). Depending on /// the operation, the semantic interpretation may be unsigned integer, signed /// integer or bit string. -pub fn int_custom_type(width_arg: impl Into) -> CustomType { +pub fn int_custom_type( + width_arg: impl Into, + extension_ref: &Weak, +) -> CustomType { CustomType::new( INT_TYPE_ID, [width_arg.into()], EXTENSION_ID, TypeBound::Copyable, + extension_ref, ) } @@ -39,7 +43,7 @@ pub fn int_custom_type(width_arg: impl Into) -> CustomType { /// /// Constructed from [int_custom_type]. pub fn int_type(width_arg: impl Into) -> Type { - Type::new_extension(int_custom_type(width_arg.into())) + int_custom_type(width_arg.into(), &Arc::::downgrade(&EXTENSION)).into() } lazy_static! { @@ -187,7 +191,7 @@ impl CustomConst for ConstInt { } /// Extension for basic integer types. -pub fn extension() -> Arc { +fn extension() -> Arc { Extension::new_arc(EXTENSION_ID, VERSION, |extension, extension_ref| { extension .add_type( diff --git a/hugr-core/src/std_extensions/collections.rs b/hugr-core/src/std_extensions/collections.rs index 6a82da334..a26adfecb 100644 --- a/hugr-core/src/std_extensions/collections.rs +++ b/hugr-core/src/std_extensions/collections.rs @@ -12,7 +12,7 @@ use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; use strum_macros::{EnumIter, EnumString, IntoStaticStr}; -use crate::extension::prelude::{either_type, option_type, USIZE_T}; +use crate::extension::prelude::{either_type, option_type, usize_t}; use crate::extension::simple_op::{MakeOpDef, MakeRegisteredOp}; use crate::extension::{ExtensionBuildError, OpDef, SignatureFunc, PRELUDE}; use crate::ops::constant::{maybe_hash_values, TryHash, ValueName}; @@ -175,21 +175,23 @@ impl ListOp { .into(), push => self.list_polytype(vec![l.clone(), e], vec![l]).into(), get => self - .list_polytype(vec![l, USIZE_T], vec![Type::from(option_type(e))]) + .list_polytype(vec![l, usize_t()], vec![Type::from(option_type(e))]) .into(), set => self .list_polytype( - vec![l.clone(), USIZE_T, e.clone()], + vec![l.clone(), usize_t(), e.clone()], vec![l, Type::from(either_type(e.clone(), e))], ) .into(), insert => self .list_polytype( - vec![l.clone(), USIZE_T, e.clone()], + vec![l.clone(), usize_t(), e.clone()], vec![l, either_type(e, Type::UNIT).into()], ) .into(), - length => self.list_polytype(vec![l.clone()], vec![l, USIZE_T]).into(), + length => self + .list_polytype(vec![l.clone()], vec![l, usize_t()]) + .into(), } } @@ -221,6 +223,10 @@ impl MakeOpDef for ListOp { EXTENSION_ID.to_owned() } + fn extension_ref(&self) -> Weak { + Arc::downgrade(&EXTENSION) + } + /// Add an operation implemented as an [MakeOpDef], which can provide the data /// required to define an [OpDef], to an extension. // @@ -239,7 +245,7 @@ impl MakeOpDef for ListOp { Ok(()) } - fn signature(&self) -> SignatureFunc { + fn init_signature(&self, _extension_ref: &Weak) -> SignatureFunc { self.compute_signature(list_type_def()) } @@ -390,10 +396,10 @@ mod test { use crate::PortIndex; use crate::{ extension::{ - prelude::{ConstUsize, QB_T, USIZE_T}, + prelude::{qb_t, usize_t, ConstUsize}, PRELUDE, }, - std_extensions::arithmetic::float_types::{self, ConstF64, FLOAT64_TYPE}, + std_extensions::arithmetic::float_types::{self, float64_type, ConstF64}, types::TypeRow, }; @@ -414,7 +420,7 @@ mod test { let list_def = list_type_def(); let list_type = list_def - .instantiate([TypeArg::Type { ty: USIZE_T }]) + .instantiate([TypeArg::Type { ty: usize_t() }]) .unwrap(); assert!(list_def @@ -422,11 +428,11 @@ mod test { .is_err()); list_def.check_custom(&list_type).unwrap(); - let list_value = ListValue(vec![ConstUsize::new(3).into()], USIZE_T); + let list_value = ListValue(vec![ConstUsize::new(3).into()], usize_t()); list_value.validate().unwrap(); - let wrong_list_value = ListValue(vec![ConstF64::new(1.2).into()], USIZE_T); + let wrong_list_value = ListValue(vec![ConstF64::new(1.2).into()], usize_t()); assert!(wrong_list_value.validate().is_err()); } @@ -435,26 +441,26 @@ mod test { let reg = ExtensionRegistry::try_new([PRELUDE.to_owned(), float_types::EXTENSION.to_owned()]) .unwrap(); - let pop_op = ListOp::pop.with_type(QB_T); + let pop_op = ListOp::pop.with_type(qb_t()); let pop_ext = pop_op.clone().to_extension_op(®).unwrap(); assert_eq!(ListOpInst::from_extension_op(&pop_ext).unwrap(), pop_op); let pop_sig = pop_ext.dataflow_signature().unwrap(); - let list_t = list_type(QB_T); + let list_t = list_type(qb_t()); - let both_row: TypeRow = vec![list_t.clone(), option_type(QB_T).into()].into(); + let both_row: TypeRow = vec![list_t.clone(), option_type(qb_t()).into()].into(); let just_list_row: TypeRow = vec![list_t].into(); assert_eq!(pop_sig.input(), &just_list_row); assert_eq!(pop_sig.output(), &both_row); - let push_op = ListOp::push.with_type(FLOAT64_TYPE); + let push_op = ListOp::push.with_type(float64_type()); let push_ext = push_op.clone().to_extension_op(®).unwrap(); assert_eq!(ListOpInst::from_extension_op(&push_ext).unwrap(), push_op); let push_sig = push_ext.dataflow_signature().unwrap(); - let list_t = list_type(FLOAT64_TYPE); + let list_t = list_type(float64_type()); - let both_row: TypeRow = vec![list_t.clone(), FLOAT64_TYPE].into(); + let both_row: TypeRow = vec![list_t.clone(), float64_type()].into(); let just_list_row: TypeRow = vec![list_t].into(); assert_eq!(push_sig.input(), &both_row); @@ -483,7 +489,7 @@ mod test { .iter() .map(|&i| Value::extension(ConstUsize::new(i as u64))) .collect(); - Value::extension(ListValue(elems, USIZE_T)) + Value::extension(ListValue(elems, usize_t())) } TestVal::Some(l) => { let elems = l.iter().map(TestVal::to_value); @@ -504,13 +510,13 @@ mod test { #[rstest] #[case::pop(ListOp::pop, &[TestVal::List(vec![77,88, 42])], &[TestVal::List(vec![77,88]), TestVal::Some(vec![TestVal::Elem(42)])])] - #[case::pop_empty(ListOp::pop, &[TestVal::List(vec![])], &[TestVal::List(vec![]), TestVal::None(vec![USIZE_T].into())])] + #[case::pop_empty(ListOp::pop, &[TestVal::List(vec![])], &[TestVal::List(vec![]), TestVal::None(vec![usize_t()].into())])] #[case::push(ListOp::push, &[TestVal::List(vec![77,88]), TestVal::Elem(42)], &[TestVal::List(vec![77,88,42])])] - #[case::set(ListOp::set, &[TestVal::List(vec![77,88,42]), TestVal::Idx(1), TestVal::Elem(99)], &[TestVal::List(vec![77,99,42]), TestVal::Ok(vec![TestVal::Elem(88)], vec![USIZE_T].into())])] - #[case::set_invalid(ListOp::set, &[TestVal::List(vec![77,88,42]), TestVal::Idx(123), TestVal::Elem(99)], &[TestVal::List(vec![77,88,42]), TestVal::Err(vec![USIZE_T].into(), vec![TestVal::Elem(99)])])] + #[case::set(ListOp::set, &[TestVal::List(vec![77,88,42]), TestVal::Idx(1), TestVal::Elem(99)], &[TestVal::List(vec![77,99,42]), TestVal::Ok(vec![TestVal::Elem(88)], vec![usize_t()].into())])] + #[case::set_invalid(ListOp::set, &[TestVal::List(vec![77,88,42]), TestVal::Idx(123), TestVal::Elem(99)], &[TestVal::List(vec![77,88,42]), TestVal::Err(vec![usize_t()].into(), vec![TestVal::Elem(99)])])] #[case::get(ListOp::get, &[TestVal::List(vec![77,88,42]), TestVal::Idx(1)], &[TestVal::Some(vec![TestVal::Elem(88)])])] - #[case::get_invalid(ListOp::get, &[TestVal::List(vec![77,88,42]), TestVal::Idx(99)], &[TestVal::None(vec![USIZE_T].into())])] - #[case::insert(ListOp::insert, &[TestVal::List(vec![77,88,42]), TestVal::Idx(1), TestVal::Elem(99)], &[TestVal::List(vec![77,99,88,42]), TestVal::Ok(vec![], vec![USIZE_T].into())])] + #[case::get_invalid(ListOp::get, &[TestVal::List(vec![77,88,42]), TestVal::Idx(99)], &[TestVal::None(vec![usize_t()].into())])] + #[case::insert(ListOp::insert, &[TestVal::List(vec![77,88,42]), TestVal::Idx(1), TestVal::Elem(99)], &[TestVal::List(vec![77,99,88,42]), TestVal::Ok(vec![], vec![usize_t()].into())])] #[case::insert_invalid(ListOp::insert, &[TestVal::List(vec![77,88,42]), TestVal::Idx(52), TestVal::Elem(99)], &[TestVal::List(vec![77,88,42]), TestVal::Err(Type::UNIT.into(), vec![TestVal::Elem(99)])])] #[case::length(ListOp::length, &[TestVal::List(vec![77,88,42])], &[TestVal::Elem(3)])] fn list_fold(#[case] op: ListOp, #[case] inputs: &[TestVal], #[case] outputs: &[TestVal]) { @@ -521,7 +527,7 @@ mod test { .collect(); let res = op - .with_type(USIZE_T) + .with_type(usize_t()) .to_extension_op(&COLLECTIONS_REGISTRY) .unwrap() .constant_fold(&consts) diff --git a/hugr-core/src/std_extensions/logic.rs b/hugr-core/src/std_extensions/logic.rs index 4799e3f33..a4f73ed4f 100644 --- a/hugr-core/src/std_extensions/logic.rs +++ b/hugr-core/src/std_extensions/logic.rs @@ -1,6 +1,6 @@ //! Basic logical operations. -use std::sync::Arc; +use std::sync::{Arc, Weak}; use strum_macros::{EnumIter, EnumString, IntoStaticStr}; @@ -10,11 +10,11 @@ use crate::ops::Value; use crate::types::Signature; use crate::{ extension::{ - prelude::BOOL_T, + prelude::bool_t, simple_op::{try_from_name, MakeOpDef, MakeRegisteredOp, OpLoadError}, ExtensionId, ExtensionRegistry, OpDef, SignatureFunc, }, - ops, type_row, + ops, types::type_param::TypeArg, utils::sorted_consts, Extension, IncomingPort, @@ -70,16 +70,20 @@ pub enum LogicOp { } impl MakeOpDef for LogicOp { - fn signature(&self) -> SignatureFunc { + fn init_signature(&self, _extension_ref: &Weak) -> SignatureFunc { match self { LogicOp::And | LogicOp::Or | LogicOp::Eq => { - Signature::new(type_row![BOOL_T; 2], type_row![BOOL_T]) + Signature::new(vec![bool_t(); 2], vec![bool_t()]) } - LogicOp::Not => Signature::new_endo(type_row![BOOL_T]), + LogicOp::Not => Signature::new_endo(vec![bool_t()]), } .into() } + fn extension_ref(&self) -> Weak { + Arc::downgrade(&EXTENSION) + } + fn description(&self) -> String { match self { LogicOp::And => "logical 'and'", @@ -166,7 +170,7 @@ pub(crate) mod test { use super::{extension, LogicOp, FALSE_NAME, TRUE_NAME}; use crate::{ extension::{ - prelude::BOOL_T, + prelude::bool_t, simple_op::{MakeOpDef, MakeRegisteredOp}, }, ops::{NamedOp, Value}, @@ -206,16 +210,16 @@ pub(crate) mod test { for v in [false_val, true_val] { let simpl = v.typed_value().get_type(); - assert_eq!(simpl, BOOL_T); + assert_eq!(simpl, bool_t()); } } - /// Generate a logic extension "and" operation over [`crate::prelude::BOOL_T`] + /// Generate a logic extension "and" operation over [`crate::prelude::bool_t()`] pub(crate) fn and_op() -> LogicOp { LogicOp::And } - /// Generate a logic extension "or" operation over [`crate::prelude::BOOL_T`] + /// Generate a logic extension "or" operation over [`crate::prelude::bool_t()`] pub(crate) fn or_op() -> LogicOp { LogicOp::Or } diff --git a/hugr-core/src/std_extensions/ptr.rs b/hugr-core/src/std_extensions/ptr.rs index 1822967b7..774ea10eb 100644 --- a/hugr-core/src/std_extensions/ptr.rs +++ b/hugr-core/src/std_extensions/ptr.rs @@ -1,6 +1,6 @@ //! Pointer type and operations. -use std::sync::Arc; +use std::sync::{Arc, Weak}; use strum_macros::{EnumIter, EnumString, IntoStaticStr}; @@ -50,8 +50,9 @@ impl MakeOpDef for PtrOpDef { crate::extension::simple_op::try_from_name(op_def.name(), op_def.extension_id()) } - fn signature(&self) -> SignatureFunc { - let ptr_t = ptr_type(Type::new_var_use(0, TypeBound::Copyable)); + fn init_signature(&self, extension_ref: &Weak) -> SignatureFunc { + let ptr_t: Type = + ptr_custom_type(Type::new_var_use(0, TypeBound::Copyable), extension_ref).into(); let inner_t = Type::new_var_use(0, TypeBound::Copyable); let body = match self { PtrOpDef::New => Signature::new(inner_t, ptr_t), @@ -66,6 +67,10 @@ impl MakeOpDef for PtrOpDef { EXTENSION_ID } + fn extension_ref(&self) -> Weak { + Arc::downgrade(&EXTENSION) + } + fn description(&self) -> String { match self { PtrOpDef::New => "Create a new pointer from a value.".into(), @@ -112,16 +117,20 @@ lazy_static! { /// Integer type of a given bit width (specified by the TypeArg). Depending on /// the operation, the semantic interpretation may be unsigned integer, signed /// integer or bit string. -pub fn ptr_custom_type(ty: impl Into) -> CustomType { +fn ptr_custom_type(ty: impl Into, extension_ref: &Weak) -> CustomType { let ty = ty.into(); - CustomType::new(PTR_TYPE_ID, [ty.into()], EXTENSION_ID, TypeBound::Copyable) + CustomType::new( + PTR_TYPE_ID, + [ty.into()], + EXTENSION_ID, + TypeBound::Copyable, + extension_ref, + ) } /// Integer type of a given bit width (specified by the TypeArg). -/// -/// Constructed from [ptr_custom_type]. pub fn ptr_type(ty: impl Into) -> Type { - Type::new_extension(ptr_custom_type(ty)) + ptr_custom_type(ty, &Arc::::downgrade(&EXTENSION)).into() } #[derive(Clone, Debug, PartialEq)] @@ -215,7 +224,7 @@ impl HasDef for PtrOp { #[cfg(test)] pub(crate) mod test { use crate::builder::DFGBuilder; - use crate::extension::prelude::BOOL_T; + use crate::extension::prelude::bool_t; use crate::ops::ExtensionOp; use crate::{ builder::{Dataflow, DataflowHugr}, @@ -228,7 +237,7 @@ pub(crate) mod test { use super::*; use crate::std_extensions::arithmetic::float_types::{ - EXTENSION as FLOAT_EXTENSION, FLOAT64_TYPE, + float64_type, EXTENSION as FLOAT_EXTENSION, }; fn get_opdef(op: impl NamedOp) -> Option<&'static Arc> { EXTENSION.get_op(&op.name()) @@ -246,8 +255,8 @@ pub(crate) mod test { #[test] fn test_ops() { let ops = [ - PtrOp::new(PtrOpDef::New, BOOL_T.clone()), - PtrOp::new(PtrOpDef::Read, FLOAT64_TYPE.clone()), + PtrOp::new(PtrOpDef::New, bool_t().clone()), + PtrOp::new(PtrOpDef::Read, float64_type()), PtrOp::new(PtrOpDef::Write, INT_TYPES[5].clone()), ]; for op in ops { @@ -261,7 +270,7 @@ pub(crate) mod test { #[test] fn test_build() { - let in_row = vec![BOOL_T, FLOAT64_TYPE]; + let in_row = vec![bool_t(), float64_type()]; let reg = ExtensionRegistry::try_new([EXTENSION.to_owned(), FLOAT_EXTENSION.to_owned()]).unwrap(); diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index c61149bff..aade935d4 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -613,20 +613,24 @@ pub(crate) fn check_typevar_decl( #[cfg(test)] pub(crate) mod test { + use std::sync::Weak; + use super::*; - use crate::extension::prelude::USIZE_T; + use crate::extension::prelude::usize_t; use crate::type_row; #[test] fn construct() { let t: Type = Type::new_tuple(vec![ - USIZE_T, + usize_t(), Type::new_function(Signature::new_endo(vec![])), Type::new_extension(CustomType::new( "my_custom", [], "my_extension".try_into().unwrap(), TypeBound::Copyable, + // Dummy extension reference. + &Weak::default(), )), Type::new_alias(AliasDecl::new("my_alias", TypeBound::Copyable)), ]); diff --git a/hugr-core/src/types/custom.rs b/hugr-core/src/types/custom.rs index e38bde9cf..c8eed491e 100644 --- a/hugr-core/src/types/custom.rs +++ b/hugr-core/src/types/custom.rs @@ -2,8 +2,10 @@ //! //! [`Type`]: super::Type use std::fmt::{self, Display}; +use std::sync::Weak; use crate::extension::{ExtensionId, ExtensionRegistry, SignatureError, TypeDef}; +use crate::Extension; use super::{ type_param::{TypeArg, TypeParam}, @@ -12,9 +14,13 @@ use super::{ use super::{Type, TypeName}; /// An opaque type element. Contains the unique identifier of its definition. -#[derive(Debug, PartialEq, Eq, Clone, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct CustomType { + /// The identifier for the extension owning this type. extension: ExtensionId, + /// A weak reference to the extension defining this type. + #[serde(skip)] + extension_ref: Weak, /// Unique identifier of the opaque type. /// Same as the corresponding [`TypeDef`] /// @@ -28,6 +34,26 @@ pub struct CustomType { bound: TypeBound, } +impl std::hash::Hash for CustomType { + fn hash(&self, state: &mut H) { + self.extension.hash(state); + self.id.hash(state); + self.args.hash(state); + self.bound.hash(state); + } +} + +impl PartialEq for CustomType { + fn eq(&self, other: &Self) -> bool { + self.extension == other.extension + && self.id == other.id + && self.args == other.args + && self.bound == other.bound + } +} + +impl Eq for CustomType {} + impl CustomType { /// Creates a new opaque type. pub fn new( @@ -35,22 +61,14 @@ impl CustomType { args: impl Into>, extension: ExtensionId, bound: TypeBound, + extension_ref: &Weak, ) -> Self { Self { id: id.into(), args: args.into(), extension, bound, - } - } - - /// Creates a new opaque type (constant version, no type arguments) - pub const fn new_simple(id: TypeName, extension: ExtensionId, bound: TypeBound) -> Self { - Self { - id, - args: vec![], - extension, - bound, + extension_ref: extension_ref.clone(), } } @@ -120,6 +138,11 @@ impl CustomType { pub fn extension(&self) -> &ExtensionId { &self.extension } + + /// Returns a weak reference to the extension defining this type. + pub fn extension_ref(&self) -> Weak { + self.extension_ref.clone() + } } impl Display for CustomType { @@ -142,6 +165,8 @@ impl From for Type { mod test { pub mod proptest { + use std::sync::Weak; + use crate::extension::ExtensionId; use crate::proptest::any_nonempty_string; use crate::proptest::RecursionDepth; @@ -184,7 +209,9 @@ mod test { vec(any_with::(depth.descend()), 0..3).boxed() }; (any_nonempty_string(), args, any::(), bound) - .prop_map(|(id, args, extension, bound)| Self::new(id, args, extension, bound)) + .prop_map(|(id, args, extension, bound)| { + Self::new(id, args, extension, bound, &Weak::default()) + }) .boxed() } } diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index 77c4ab990..5882d377f 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -150,11 +150,12 @@ impl PolyFuncTypeBase { #[cfg(test)] pub(crate) mod test { use std::num::NonZeroU64; + use std::sync::Arc; use cool_asserts::assert_matches; use lazy_static::lazy_static; - use crate::extension::prelude::{BOOL_T, PRELUDE_ID, USIZE_T}; + use crate::extension::prelude::{bool_t, usize_t, PRELUDE_ID}; use crate::extension::{ ExtensionId, ExtensionRegistry, SignatureError, TypeDefBound, EMPTY_REG, PRELUDE, PRELUDE_REGISTRY, @@ -193,20 +194,20 @@ pub(crate) mod test { let list_of_var = Type::new_extension(list_def.instantiate([tyvar.clone()])?); let list_len = PolyFuncTypeBase::new_validated( [TypeBound::Any.into()], - Signature::new(vec![list_of_var], vec![USIZE_T]), + Signature::new(vec![list_of_var], vec![usize_t()]), ®ISTRY, )?; - let t = list_len.instantiate(&[TypeArg::Type { ty: USIZE_T }], ®ISTRY)?; + let t = list_len.instantiate(&[TypeArg::Type { ty: usize_t() }], ®ISTRY)?; assert_eq!( t, Signature::new( vec![Type::new_extension( list_def - .instantiate([TypeArg::Type { ty: USIZE_T }]) + .instantiate([TypeArg::Type { ty: usize_t() }]) .unwrap() )], - vec![USIZE_T] + vec![usize_t()] ) ); @@ -230,12 +231,18 @@ pub(crate) mod test { // Sanity check (good args) good_ts.instantiate( - &[TypeArg::BoundedNat { n: 5 }, TypeArg::Type { ty: USIZE_T }], + &[ + TypeArg::BoundedNat { n: 5 }, + TypeArg::Type { ty: usize_t() }, + ], &PRELUDE_REGISTRY, )?; let wrong_args = good_ts.instantiate( - &[TypeArg::Type { ty: USIZE_T }, TypeArg::BoundedNat { n: 5 }], + &[ + TypeArg::Type { ty: usize_t() }, + TypeArg::BoundedNat { n: 5 }, + ], &PRELUDE_REGISTRY, ); assert_eq!( @@ -243,7 +250,7 @@ pub(crate) mod test { Err(SignatureError::TypeArgMismatch( TypeArgError::TypeMismatch { param: typarams[0].clone(), - arg: TypeArg::Type { ty: USIZE_T } + arg: TypeArg::Type { ty: usize_t() } } )) ); @@ -263,6 +270,7 @@ pub(crate) mod test { [szvar, tyvar], PRELUDE_ID, TypeBound::Any, + &Arc::downgrade(&PRELUDE), )); let bad_ts = PolyFuncTypeBase::new_validated( typarams.clone(), @@ -332,7 +340,7 @@ pub(crate) mod test { .unwrap(); }); - let reg = ExtensionRegistry::try_new([ext]).unwrap(); + let reg = ExtensionRegistry::try_new([ext.clone()]).unwrap(); let make_scheme = |tp: TypeParam| { PolyFuncTypeBase::new_validated( @@ -342,6 +350,7 @@ pub(crate) mod test { [TypeArg::new_var_use(0, tp)], EXT_ID, TypeBound::Any, + &Arc::downgrade(&ext), ))), ®, ) @@ -403,7 +412,7 @@ pub(crate) mod test { let e = PolyFuncTypeBase::new_validated( [decl.clone()], FuncValueType::new( - vec![USIZE_T], + vec![usize_t()], vec![TypeRV::new_row_var_use(0, TypeBound::Copyable)], ), &PRELUDE_REGISTRY, @@ -432,7 +441,7 @@ pub(crate) mod test { let pf = PolyFuncTypeBase::new_validated( [TypeParam::new_list(TP_ANY)], FuncValueType::new( - vec![USIZE_T.into(), rty.clone()], + vec![usize_t().into(), rty.clone()], vec![TypeRV::new_tuple(rty)], ), &PRELUDE_REGISTRY, @@ -440,13 +449,13 @@ pub(crate) mod test { .unwrap(); fn seq2() -> Vec { - vec![USIZE_T.into(), BOOL_T.into()] + vec![usize_t().into(), bool_t().into()] } - pf.instantiate(&[TypeArg::Type { ty: USIZE_T }], &PRELUDE_REGISTRY) + pf.instantiate(&[TypeArg::Type { ty: usize_t() }], &PRELUDE_REGISTRY) .unwrap_err(); pf.instantiate( &[TypeArg::Sequence { - elems: vec![USIZE_T.into(), TypeArg::Sequence { elems: seq2() }], + elems: vec![usize_t().into(), TypeArg::Sequence { elems: seq2() }], }], &PRELUDE_REGISTRY, ) @@ -458,8 +467,8 @@ pub(crate) mod test { assert_eq!( t2, Signature::new( - vec![USIZE_T, USIZE_T, BOOL_T], - vec![Type::new_tuple(vec![USIZE_T, BOOL_T])] + vec![usize_t(), usize_t(), bool_t()], + vec![Type::new_tuple(vec![usize_t(), bool_t()])] ) ); } @@ -476,23 +485,23 @@ pub(crate) mod test { b: TypeBound::Copyable, }), }], - Signature::new(vec![USIZE_T, inner_fty.clone()], vec![inner_fty]), + Signature::new(vec![usize_t(), inner_fty.clone()], vec![inner_fty]), &PRELUDE_REGISTRY, ) .unwrap(); - let inner3 = Type::new_function(Signature::new_endo(vec![USIZE_T, BOOL_T, USIZE_T])); + let inner3 = Type::new_function(Signature::new_endo(vec![usize_t(), bool_t(), usize_t()])); let t3 = pf .instantiate( &[TypeArg::Sequence { - elems: vec![USIZE_T.into(), BOOL_T.into(), USIZE_T.into()], + elems: vec![usize_t().into(), bool_t().into(), usize_t().into()], }], &PRELUDE_REGISTRY, ) .unwrap(); assert_eq!( t3, - Signature::new(vec![USIZE_T, inner3.clone()], vec![inner3]) + Signature::new(vec![usize_t(), inner3.clone()], vec![inner3]) ); } } diff --git a/hugr-core/src/types/serialize.rs b/hugr-core/src/types/serialize.rs index de1f94da1..74d1be6e8 100644 --- a/hugr-core/src/types/serialize.rs +++ b/hugr-core/src/types/serialize.rs @@ -2,7 +2,7 @@ use super::{FuncValueType, MaybeRV, RowVariable, SumType, TypeArg, TypeBase, Typ use super::custom::CustomType; -use crate::extension::prelude::{array_type, QB_T, USIZE_T}; +use crate::extension::prelude::{array_type, qb_t, usize_t}; use crate::extension::SignatureError; use crate::ops::AliasDecl; @@ -22,10 +22,10 @@ pub(super) enum SerSimpleType { impl From> for SerSimpleType { fn from(value: TypeBase) -> Self { - if value == QB_T { + if value == qb_t() { return SerSimpleType::Q; }; - if value == USIZE_T { + if value == usize_t() { return SerSimpleType::I; }; match value.0 { @@ -46,8 +46,8 @@ impl TryFrom for TypeBase { type Error = SignatureError; fn try_from(value: SerSimpleType) -> Result { Ok(match value { - SerSimpleType::Q => QB_T.into_(), - SerSimpleType::I => USIZE_T.into_(), + SerSimpleType::Q => qb_t().into_(), + SerSimpleType::I => usize_t().into_(), SerSimpleType::G(sig) => TypeBase::new_function(*sig), SerSimpleType::Sum(st) => st.into(), SerSimpleType::Array { inner, len } => { diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index ee0164087..faf56abd2 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -298,7 +298,7 @@ impl PartialEq> for FuncTypeBase PolyFuncTypeRV { - FuncValueType::new_endo(QB_T).into() + FuncValueType::new_endo(qb_t()).into() } fn two_qb_func() -> PolyFuncTypeRV { - FuncValueType::new_endo(type_row![QB_T, QB_T]).into() + FuncValueType::new_endo(vec![qb_t(), qb_t()]).into() } /// The extension identifier. pub const EXTENSION_ID: ExtensionId = ExtensionId::new_unchecked("test.quantum"); @@ -144,7 +144,7 @@ pub(crate) mod test_quantum_extension { .add_op( OpName::new_inline("RzF64"), "Rotation specified by float".into(), - Signature::new(type_row![QB_T, float_types::FLOAT64_TYPE], type_row![QB_T]), + Signature::new(vec![qb_t(), float_types::float64_type()], vec![qb_t()]), extension_ref, ) .unwrap(); @@ -162,7 +162,7 @@ pub(crate) mod test_quantum_extension { .add_op( OpName::new_inline("Measure"), "Measure a qubit, returning the qubit and the measurement result.".into(), - Signature::new(type_row![QB_T], type_row![QB_T, BOOL_T]), + Signature::new(vec![qb_t()], vec![qb_t(), bool_t()]), extension_ref, ) .unwrap(); @@ -171,7 +171,7 @@ pub(crate) mod test_quantum_extension { .add_op( OpName::new_inline("QAlloc"), "Allocate a new qubit.".into(), - Signature::new(type_row![], type_row![QB_T]), + Signature::new(type_row![], vec![qb_t()]), extension_ref, ) .unwrap(); @@ -180,7 +180,7 @@ pub(crate) mod test_quantum_extension { .add_op( OpName::new_inline("QDiscard"), "Discard a qubit.".into(), - Signature::new(type_row![QB_T], type_row![]), + Signature::new(vec![qb_t()], type_row![]), extension_ref, ) .unwrap(); diff --git a/hugr-core/tests/snapshots/model__roundtrip_constraints.snap b/hugr-core/tests/snapshots/model__roundtrip_constraints.snap index f085c4785..291c2de48 100644 --- a/hugr-core/tests/snapshots/model__roundtrip_constraints.snap +++ b/hugr-core/tests/snapshots/model__roundtrip_constraints.snap @@ -8,9 +8,9 @@ expression: "roundtrip(include_str!(\"../../hugr-model/tests/fixtures/model-cons (forall ?0 type) (forall ?1 nat) (where (nonlinear ?0)) - [?0] [(@ array.Array ?0 ?1)] (ext)) + [?0] [(@ prelude.Array ?0 ?1)] (ext)) (declare-func array.copy (forall ?0 type) (where (nonlinear ?0)) - [(@ array.Array ?0)] [(@ array.Array ?0) (@ array.Array ?0)] (ext)) + [(@ prelude.Array ?0)] [(@ prelude.Array ?0) (@ prelude.Array ?0)] (ext)) diff --git a/hugr-llvm/src/custom.rs b/hugr-llvm/src/custom.rs index c5e384d29..3c4525954 100644 --- a/hugr-llvm/src/custom.rs +++ b/hugr-llvm/src/custom.rs @@ -156,7 +156,7 @@ pub struct CodegenExtsMap<'a, H> { #[cfg(test)] mod test { use hugr_core::{ - extension::prelude::{ConstString, PRELUDE_ID, PRINT_OP_ID, STRING_TYPE, STRING_TYPE_NAME}, + extension::prelude::{string_type, ConstString, PRELUDE_ID, PRINT_OP_ID, STRING_TYPE_NAME}, Hugr, }; use inkwell::{ @@ -187,7 +187,7 @@ mod test { let ty = cem .type_converter .session(&ctx) - .llvm_type(&STRING_TYPE) + .llvm_type(&string_type()) .unwrap() .into_struct_type(); let ty_n = ty.get_name().unwrap().to_str().unwrap(); diff --git a/hugr-llvm/src/emit/ops/cfg.rs b/hugr-llvm/src/emit/ops/cfg.rs index fe66fb312..44fe2d410 100644 --- a/hugr-llvm/src/emit/ops/cfg.rs +++ b/hugr-llvm/src/emit/ops/cfg.rs @@ -218,7 +218,7 @@ impl<'c, 'hugr, H: HugrView> CfgEmitter<'c, 'hugr, H> { #[cfg(test)] mod test { use hugr_core::builder::{Dataflow, DataflowSubContainer, SubContainer}; - use hugr_core::extension::prelude::{self, BOOL_T}; + use hugr_core::extension::prelude::{self, bool_t}; use hugr_core::extension::{ExtensionRegistry, ExtensionSet}; use hugr_core::ops::Value; use hugr_core::std_extensions::arithmetic::int_types::{self, INT_TYPES}; @@ -245,8 +245,11 @@ mod test { .with_ins(vec![t1.clone(), t2.clone()]) .with_outs(t2.clone()) .with_extensions( - ExtensionRegistry::try_new([int_types::extension(), prelude::PRELUDE.to_owned()]) - .unwrap(), + ExtensionRegistry::try_new([ + int_types::EXTENSION.to_owned(), + prelude::PRELUDE.to_owned(), + ]) + .unwrap(), ) .finish(|mut builder| { let [in1, in2] = builder.input_wires_arr(); @@ -295,14 +298,14 @@ mod test { fn nested(llvm_ctx: TestContext) { let t1 = HugrType::new_unit_sum(3); let hugr = SimpleHugrConfig::new() - .with_ins(vec![t1.clone(), BOOL_T]) - .with_outs(BOOL_T) + .with_ins(vec![t1.clone(), bool_t()]) + .with_outs(bool_t()) .finish(|mut builder| { let [in1, in2] = builder.input_wires_arr(); let unit_val = builder.add_load_value(Value::unit()); let [outer_cfg_out] = { let mut outer_cfg_builder = builder - .cfg_builder([(t1.clone(), in1), (BOOL_T, in2)], BOOL_T.into()) + .cfg_builder([(t1.clone(), in1), (bool_t(), in2)], bool_t().into()) .unwrap(); let outer_entry_block = { @@ -312,8 +315,9 @@ mod test { let [outer_entry_in1, outer_entry_in2] = outer_entry_builder.input_wires_arr(); let [outer_entry_out] = { - let mut inner_cfg_builder = - outer_entry_builder.cfg_builder([], BOOL_T.into()).unwrap(); + let mut inner_cfg_builder = outer_entry_builder + .cfg_builder([], bool_t().into()) + .unwrap(); let inner_exit_block = inner_cfg_builder.exit_block(); let inner_entry_block = { let inner_entry_builder = inner_cfg_builder @@ -333,7 +337,7 @@ mod test { .block_builder( type_row![], vec![type_row![]], - BOOL_T.into(), + bool_t().into(), ) .unwrap(); let output = match i { @@ -373,7 +377,7 @@ mod test { let [b1, b2] = (0..2) .map(|i| { let mut b_builder = outer_cfg_builder - .block_builder(type_row![], vec![type_row![]], BOOL_T.into()) + .block_builder(type_row![], vec![type_row![]], bool_t().into()) .unwrap(); let output = match i { 0 => b_builder.add_load_value(Value::true_val()), diff --git a/hugr-llvm/src/emit/test.rs b/hugr-llvm/src/emit/test.rs index 632224946..f1c9eda8c 100644 --- a/hugr-llvm/src/emit/test.rs +++ b/hugr-llvm/src/emit/test.rs @@ -250,7 +250,7 @@ mod test_fns { use hugr_core::builder::DataflowSubContainer; use hugr_core::builder::{Container, Dataflow, HugrBuilder, ModuleBuilder, SubContainer}; - use hugr_core::extension::prelude::{ConstUsize, BOOL_T, USIZE_T}; + use hugr_core::extension::prelude::{bool_t, usize_t, ConstUsize}; use hugr_core::extension::{EMPTY_REG, PRELUDE_REGISTRY}; use hugr_core::ops::constant::CustomConst; @@ -378,8 +378,8 @@ mod test_fns { let mut mod_b = ModuleBuilder::new(); build_recursive(&mut mod_b, "main_void", type_row![]); - build_recursive(&mut mod_b, "main_unary", type_row![BOOL_T]); - build_recursive(&mut mod_b, "main_binary", type_row![BOOL_T, BOOL_T]); + build_recursive(&mut mod_b, "main_unary", vec![bool_t()].into()); + build_recursive(&mut mod_b, "main_binary", vec![bool_t(), bool_t()].into()); let hugr = mod_b.finish_hugr(&EMPTY_REG).unwrap(); check_emission!(hugr, llvm_ctx); } @@ -400,8 +400,8 @@ mod test_fns { let mut mod_b = ModuleBuilder::new(); build_recursive(&mut mod_b, "main_void", type_row![]); - build_recursive(&mut mod_b, "main_unary", type_row![BOOL_T]); - build_recursive(&mut mod_b, "main_binary", type_row![BOOL_T, BOOL_T]); + build_recursive(&mut mod_b, "main_unary", vec![bool_t()].into()); + build_recursive(&mut mod_b, "main_binary", vec![bool_t(), bool_t()].into()); let hugr = mod_b.finish_hugr(&EMPTY_REG).unwrap(); check_emission!(hugr, llvm_ctx); } @@ -467,16 +467,19 @@ mod test_fns { #[rstest] fn diverse_dfg_children(llvm_ctx: TestContext) { let hugr = SimpleHugrConfig::new() - .with_outs(BOOL_T) + .with_outs(bool_t()) .finish(|mut builder: DFGW| { let [r] = { let mut builder = builder - .dfg_builder(HugrFuncType::new(type_row![], BOOL_T), []) + .dfg_builder(HugrFuncType::new(type_row![], bool_t()), []) .unwrap(); let konst = builder.add_constant(Value::false_val()); let func = { let mut builder = builder - .define_function("scoped_func", HugrFuncType::new(type_row![], BOOL_T)) + .define_function( + "scoped_func", + HugrFuncType::new(type_row![], bool_t()), + ) .unwrap(); let w = builder.load_const(&konst); builder.finish_with_outputs([w]).unwrap() @@ -495,21 +498,24 @@ mod test_fns { #[rstest] fn diverse_cfg_children(llvm_ctx: TestContext) { let hugr = SimpleHugrConfig::new() - .with_outs(BOOL_T) + .with_outs(bool_t()) .finish(|mut builder: DFGW| { let [r] = { - let mut builder = builder.cfg_builder([], type_row![BOOL_T]).unwrap(); + let mut builder = builder.cfg_builder([], vec![bool_t()].into()).unwrap(); let konst = builder.add_constant(Value::false_val()); let func = { let mut builder = builder - .define_function("scoped_func", HugrFuncType::new(type_row![], BOOL_T)) + .define_function( + "scoped_func", + HugrFuncType::new(type_row![], bool_t()), + ) .unwrap(); let w = builder.load_const(&konst); builder.finish_with_outputs([w]).unwrap() }; let entry = { let mut builder = builder - .entry_builder([type_row![]], type_row![BOOL_T]) + .entry_builder([type_row![]], vec![bool_t()].into()) .unwrap(); let control = builder.add_load_value(Value::unary_unit_sum()); let [r] = builder @@ -554,7 +560,7 @@ mod test_fns { #[rstest] fn test_exec(mut exec_ctx: TestContext) { let hugr = SimpleHugrConfig::new() - .with_outs(USIZE_T) + .with_outs(usize_t()) .with_extensions(PRELUDE_REGISTRY.to_owned()) .finish(|mut builder: DFGW| { let konst = builder.add_load_value(ConstUsize::new(42)); diff --git a/hugr-llvm/src/extension/collections.rs b/hugr-llvm/src/extension/collections.rs index 2b8e9011a..60be7e3cd 100644 --- a/hugr-llvm/src/extension/collections.rs +++ b/hugr-llvm/src/extension/collections.rs @@ -368,7 +368,7 @@ mod test { use hugr_core::{ builder::{Dataflow, DataflowSubContainer}, extension::{ - prelude::{self, ConstUsize, QB_T, USIZE_T}, + prelude::{self, qb_t, usize_t, ConstUsize}, ExtensionRegistry, }, ops::{DataflowOpTrait, NamedOp, Value}, @@ -394,7 +394,7 @@ mod test { let ext_op = collections::EXTENSION .instantiate_extension_op( op.name().as_ref(), - [QB_T.into()], + [qb_t().into()], &collections::COLLECTIONS_REGISTRY, ) .unwrap(); @@ -421,7 +421,7 @@ mod test { #[rstest] fn test_const_list_emmission(mut llvm_ctx: TestContext) { - let elem_ty = USIZE_T; + let elem_ty = usize_t(); let contents = (1..4).map(|i| Value::extension(ConstUsize::new(i))); let es = ExtensionRegistry::try_new([ collections::EXTENSION.to_owned(), diff --git a/hugr-llvm/src/extension/conversions.rs b/hugr-llvm/src/extension/conversions.rs index 990715094..45e6fd485 100644 --- a/hugr-llvm/src/extension/conversions.rs +++ b/hugr-llvm/src/extension/conversions.rs @@ -2,7 +2,7 @@ use anyhow::{anyhow, bail, ensure, Result}; use hugr_core::{ extension::{ - prelude::{sum_with_error, ConstError, BOOL_T}, + prelude::{bool_t, sum_with_error, ConstError}, simple_op::MakeExtensionOp, }, ops::{constant::Value, custom::ExtensionOp, DataflowOpTrait as _}, @@ -179,9 +179,9 @@ fn emit_conversion_op<'c, H: HugrView>( .into_int_type(); let sum_ty = context .typing_session() - .llvm_sum_type(match BOOL_T.as_type_enum() { + .llvm_sum_type(match bool_t().as_type_enum() { TypeEnum::Sum(st) => st.clone(), - _ => panic!("Hugr prelude BOOL_T not a Sum"), + _ => panic!("Hugr prelude bool_t() not a Sum"), })?; emit_custom_unary_op(context, args, |ctx, arg, _| { @@ -254,10 +254,10 @@ mod test { use hugr_core::std_extensions::arithmetic::int_types::ConstInt; use hugr_core::{ builder::{Dataflow, DataflowSubContainer}, - extension::prelude::{ConstUsize, PRELUDE_REGISTRY, USIZE_T}, + extension::prelude::{usize_t, ConstUsize, PRELUDE_REGISTRY}, std_extensions::arithmetic::{ conversions::{ConvertOpDef, CONVERT_OPS_REGISTRY, EXTENSION}, - float_types::FLOAT64_TYPE, + float_types::float64_type, int_types::INT_TYPES, }, types::Type, @@ -302,7 +302,7 @@ mod test { .add_conversion_extensions() }); let in_ty = INT_TYPES[log_width as usize].clone(); - let out_ty = FLOAT64_TYPE; + let out_ty = float64_type(); let hugr = test_conversion_op(op_name, in_ty, out_ty, log_width); check_emission!(op_name, hugr, llvm_ctx); } @@ -322,7 +322,7 @@ mod test { .add_conversion_extensions() .add_default_prelude_extensions() }); - let in_ty = FLOAT64_TYPE; + let in_ty = float64_type(); let out_ty = sum_with_error(INT_TYPES[log_width as usize].clone()); let hugr = test_conversion_op(op_name, in_ty, out_ty.into(), log_width); check_emission!(op_name, hugr, llvm_ctx); @@ -336,7 +336,7 @@ mod test { #[case] op_name: &str, #[case] input_int: bool, ) { - let mut tys = [INT_TYPES[0].clone(), BOOL_T]; + let mut tys = [INT_TYPES[0].clone(), bool_t()]; if !input_int { tys.reverse() }; @@ -368,7 +368,7 @@ mod test { #[rstest] fn my_test_exec(mut exec_ctx: TestContext) { let hugr = SimpleHugrConfig::new() - .with_outs(USIZE_T) + .with_outs(usize_t()) .with_extensions(PRELUDE_REGISTRY.to_owned()) .finish(|mut builder: DFGW| { let konst = builder.add_load_value(ConstUsize::new(42)); @@ -384,7 +384,7 @@ mod test { #[case(18_446_744_073_709_551_615)] fn usize_roundtrip(mut exec_ctx: TestContext, #[case] val: u64) -> () { let hugr = SimpleHugrConfig::new() - .with_outs(USIZE_T) + .with_outs(usize_t()) .with_extensions(CONVERT_OPS_REGISTRY.clone()) .finish(|mut builder: DFGW| { let k = builder.add_load_value(ConstUsize::new(val)); @@ -410,7 +410,7 @@ mod test { fn roundtrip_hugr(val: u64, signed: bool) -> Hugr { let int64 = INT_TYPES[6].clone(); SimpleHugrConfig::new() - .with_outs(USIZE_T) + .with_outs(usize_t()) .with_extensions(CONVERT_OPS_REGISTRY.clone()) .finish(|mut builder| { let k = builder.add_load_value(ConstUsize::new(val)); @@ -572,7 +572,7 @@ mod test { use hugr_core::type_row; let hugr = SimpleHugrConfig::new() - .with_outs(vec![USIZE_T]) + .with_outs(vec![usize_t()]) .with_extensions(CONVERT_OPS_REGISTRY.to_owned()) .finish(|mut builder| { let i = builder.add_load_value(ConstInt::new_u(0, i).unwrap()); @@ -581,7 +581,11 @@ mod test { .unwrap(); let [b] = builder.add_dataflow_op(ext_op, [i]).unwrap().outputs_arr(); let mut cond = builder - .conditional_builder(([type_row![], type_row![]], b), [], type_row![USIZE_T]) + .conditional_builder( + ([type_row![], type_row![]], b), + [], + vec![usize_t()].into(), + ) .unwrap(); let mut case_false = cond.case_builder(0).unwrap(); let false_result = case_false.add_load_value(ConstUsize::new(1)); diff --git a/hugr-llvm/src/extension/float.rs b/hugr-llvm/src/extension/float.rs index 4aa9eae2b..7cb694cb0 100644 --- a/hugr-llvm/src/extension/float.rs +++ b/hugr-llvm/src/extension/float.rs @@ -34,7 +34,7 @@ fn emit_fcmp<'c, H: HugrView>( rhs.into_float_value(), "", )?; - // convert to whatever BOOL_T is + // convert to whatever bool_t is Ok(vec![ctx .builder() .build_select(r, true_val, false_val, "")?]) @@ -114,7 +114,7 @@ pub fn add_float_extensions<'a, H: HugrView + 'a>( cem.custom_type( ( float_types::EXTENSION_ID, - float_types::FLOAT64_CUSTOM_TYPE.name().clone(), + float_types::FLOAT_TYPE_ID.clone(), ), |ts, _custom_type| Ok(ts.iw_context().f64_type().as_basic_type_enum()), ) @@ -139,7 +139,7 @@ mod test { builder::{Dataflow, DataflowSubContainer}, std_extensions::arithmetic::{ float_ops::FLOAT_OPS_REGISTRY, - float_types::{ConstF64, FLOAT64_TYPE}, + float_types::{float64_type, ConstF64}, }, }; use rstest::rstest; @@ -176,7 +176,7 @@ mod test { fn const_float(mut llvm_ctx: TestContext) { llvm_ctx.add_extensions(add_float_extensions); let hugr = SimpleHugrConfig::new() - .with_outs(FLOAT64_TYPE) + .with_outs(float64_type()) .with_extensions(FLOAT_OPS_REGISTRY.to_owned()) .finish(|mut builder| { let c = builder.add_load_value(ConstF64::new(3.12)); diff --git a/hugr-llvm/src/extension/int.rs b/hugr-llvm/src/extension/int.rs index aa30a2a85..e6d045ceb 100644 --- a/hugr-llvm/src/extension/int.rs +++ b/hugr-llvm/src/extension/int.rs @@ -40,7 +40,7 @@ fn emit_icmp<'c, H: HugrView>( rhs.into_int_value(), "", )?; - // convert to whatever BOOL_T is + // convert to whatever bool_t is Ok(vec![ctx .builder() .build_select(r, true_val, false_val, "")?]) @@ -167,7 +167,7 @@ impl<'a, H: HugrView + 'a> CodegenExtsBuilder<'a, H> { mod test { use hugr_core::{ builder::{Dataflow, DataflowSubContainer}, - extension::prelude::BOOL_T, + extension::prelude::bool_t, std_extensions::arithmetic::{int_ops, int_types::INT_TYPES}, types::TypeRow, Hugr, @@ -187,7 +187,7 @@ mod test { } fn test_binary_icmp_op(name: impl AsRef, log_width: u8) -> Hugr { - test_binary_int_op_with_results(name, log_width, vec![BOOL_T]) + test_binary_int_op_with_results(name, log_width, vec![bool_t()]) } fn test_binary_int_op_with_results( name: impl AsRef, diff --git a/hugr-llvm/src/extension/logic.rs b/hugr-llvm/src/extension/logic.rs index 0e05e4927..88dc77a2f 100644 --- a/hugr-llvm/src/extension/logic.rs +++ b/hugr-llvm/src/extension/logic.rs @@ -93,7 +93,7 @@ impl<'a, H: HugrView + 'a> CodegenExtsBuilder<'a, H> { mod test { use hugr_core::{ builder::{Dataflow, DataflowSubContainer}, - extension::{prelude::BOOL_T, ExtensionRegistry}, + extension::{prelude::bool_t, ExtensionRegistry}, std_extensions::logic::{self, LogicOp}, Hugr, }; @@ -108,8 +108,8 @@ mod test { fn test_logic_op(op: LogicOp, arity: usize) -> Hugr { SimpleHugrConfig::new() - .with_ins(vec![BOOL_T; arity]) - .with_outs(vec![BOOL_T]) + .with_ins(vec![bool_t(); arity]) + .with_outs(vec![bool_t()]) .with_extensions(ExtensionRegistry::try_new(vec![logic::EXTENSION.to_owned()]).unwrap()) .finish(|mut builder| { let outputs = builder diff --git a/hugr-llvm/src/extension/prelude.rs b/hugr-llvm/src/extension/prelude.rs index dd5242784..445317912 100644 --- a/hugr-llvm/src/extension/prelude.rs +++ b/hugr-llvm/src/extension/prelude.rs @@ -1,10 +1,10 @@ use anyhow::{anyhow, bail, ensure, Ok, Result}; +use hugr_core::extension::prelude::{ERROR_TYPE_NAME, STRING_TYPE_NAME}; use hugr_core::{ extension::{ prelude::{ - self, ArrayOp, ArrayOpDef, ConstError, ConstExternalSymbol, ConstString, ConstUsize, - MakeTuple, TupleOpDef, UnpackTuple, ARRAY_TYPE_NAME, ERROR_CUSTOM_TYPE, ERROR_TYPE, - STRING_CUSTOM_TYPE, + self, error_type, ArrayOp, ArrayOpDef, ConstError, ConstExternalSymbol, ConstString, + ConstUsize, MakeTuple, TupleOpDef, UnpackTuple, ARRAY_TYPE_NAME, }, simple_op::MakeExtensionOp as _, }, @@ -39,18 +39,18 @@ pub mod array; /// a trivial implementation of this trait which delegates everything to those /// default implementations. pub trait PreludeCodegen: Clone { - /// Return the llvm type of [hugr_core::extension::prelude::USIZE_T]. That type + /// Return the llvm type of [hugr_core::extension::prelude::usize_t]. That type /// must be an [IntType]. fn usize_type<'c>(&self, session: &TypingSession<'c, '_>) -> IntType<'c> { session.iw_context().i64_type() } - /// Return the llvm type of [hugr_core::extension::prelude::QB_T]. + /// Return the llvm type of [hugr_core::extension::prelude::qb_t]. fn qubit_type<'c>(&self, session: &TypingSession<'c, '_>) -> impl BasicType<'c> { session.iw_context().i16_type() } - /// Return the llvm type of [hugr_core::extension::prelude::ERROR_TYPE]. + /// Return the llvm type of [hugr_core::extension::prelude::error_type()]. /// /// The returned type must always match the type of the returned value of /// [Self::emit_const_error], and the `err` argument of [Self::emit_panic]. @@ -114,7 +114,7 @@ pub trait PreludeCodegen: Clone { err: &ConstError, ) -> Result> { let builder = ctx.builder(); - let err_ty = ctx.llvm_type(&ERROR_TYPE)?.into_struct_type(); + let err_ty = ctx.llvm_type(&error_type())?.into_struct_type(); let signal = err_ty .get_field_type_at_index(0) .unwrap() @@ -222,7 +222,7 @@ fn add_prelude_extensions<'a, H: HugrView + 'a>( let pcg = pcg.clone(); move |ts, _| Ok(pcg.usize_type(&ts).as_basic_type_enum()) }) - .custom_type((prelude::PRELUDE_ID, STRING_CUSTOM_TYPE.name().clone()), { + .custom_type((prelude::PRELUDE_ID, STRING_TYPE_NAME.clone()), { move |ts, _| { // TODO allow customising string type Ok(ts @@ -232,7 +232,7 @@ fn add_prelude_extensions<'a, H: HugrView + 'a>( .into()) } }) - .custom_type((prelude::PRELUDE_ID, ERROR_CUSTOM_TYPE.name().clone()), { + .custom_type((prelude::PRELUDE_ID, ERROR_TYPE_NAME.clone()), { let pcg = pcg.clone(); move |ts, _| Ok(pcg.error_type(&ts)?.as_basic_type_enum()) }) @@ -347,7 +347,7 @@ mod test { use hugr_core::extension::{PRELUDE, PRELUDE_REGISTRY}; use hugr_core::types::{Type, TypeArg}; use hugr_core::{type_row, Hugr}; - use prelude::{BOOL_T, PANIC_OP_ID, PRINT_OP_ID, QB_T, USIZE_T}; + use prelude::{bool_t, qb_t, usize_t, PANIC_OP_ID, PRINT_OP_ID}; use rstest::rstest; use crate::check_emission; @@ -381,11 +381,11 @@ mod test { assert_eq!( iw_context.i32_type().as_basic_type_enum(), - session.llvm_type(&USIZE_T).unwrap() + session.llvm_type(&usize_t()).unwrap() ); assert_eq!( iw_context.f64_type().as_basic_type_enum(), - session.llvm_type(&QB_T).unwrap() + session.llvm_type(&qb_t()).unwrap() ); } @@ -395,11 +395,11 @@ mod test { let tc = llvm_ctx.get_typing_session(); assert_eq!( llvm_ctx.iw_context().i32_type().as_basic_type_enum(), - tc.llvm_type(&USIZE_T).unwrap() + tc.llvm_type(&usize_t()).unwrap() ); assert_eq!( llvm_ctx.iw_context().f64_type().as_basic_type_enum(), - tc.llvm_type(&QB_T).unwrap() + tc.llvm_type(&qb_t()).unwrap() ); } @@ -412,7 +412,7 @@ mod test { #[rstest] fn prelude_const_usize(prelude_llvm_ctx: TestContext) { let hugr = SimpleHugrConfig::new() - .with_outs(USIZE_T) + .with_outs(usize_t()) .with_extensions(prelude::PRELUDE_REGISTRY.to_owned()) .finish(|mut builder| { let k = builder.add_load_value(ConstUsize::new(17)); @@ -423,10 +423,13 @@ mod test { #[rstest] fn prelude_const_external_symbol(prelude_llvm_ctx: TestContext) { - let konst1 = ConstExternalSymbol::new("sym1", USIZE_T, true); + let konst1 = ConstExternalSymbol::new("sym1", usize_t(), true); let konst2 = ConstExternalSymbol::new( "sym2", - HugrType::new_sum([type_row![USIZE_T, HugrType::new_unit_sum(3)], type_row![]]), + HugrType::new_sum([ + vec![usize_t(), HugrType::new_unit_sum(3)].into(), + type_row![], + ]), false, ); @@ -444,8 +447,8 @@ mod test { #[rstest] fn prelude_make_tuple(prelude_llvm_ctx: TestContext) { let hugr = SimpleHugrConfig::new() - .with_ins(vec![BOOL_T, BOOL_T]) - .with_outs(Type::new_tuple(vec![BOOL_T, BOOL_T])) + .with_ins(vec![bool_t(), bool_t()]) + .with_outs(Type::new_tuple(vec![bool_t(), bool_t()])) .with_extensions(prelude::PRELUDE_REGISTRY.to_owned()) .finish(|mut builder| { let in_wires = builder.input_wires(); @@ -458,13 +461,13 @@ mod test { #[rstest] fn prelude_unpack_tuple(prelude_llvm_ctx: TestContext) { let hugr = SimpleHugrConfig::new() - .with_ins(Type::new_tuple(vec![BOOL_T, BOOL_T])) - .with_outs(vec![BOOL_T, BOOL_T]) + .with_ins(Type::new_tuple(vec![bool_t(), bool_t()])) + .with_outs(vec![bool_t(), bool_t()]) .with_extensions(prelude::PRELUDE_REGISTRY.to_owned()) .finish(|mut builder| { let unpack = builder .add_dataflow_op( - UnpackTuple::new(vec![BOOL_T, BOOL_T].into()), + UnpackTuple::new(vec![bool_t(), bool_t()].into()), builder.input_wires(), ) .unwrap(); @@ -476,9 +479,9 @@ mod test { #[rstest] fn prelude_panic(prelude_llvm_ctx: TestContext) { let error_val = ConstError::new(42, "PANIC"); - const TYPE_ARG_Q: TypeArg = TypeArg::Type { ty: QB_T }; + let type_arg_q: TypeArg = TypeArg::Type { ty: qb_t() }; let type_arg_2q: TypeArg = TypeArg::Sequence { - elems: vec![TYPE_ARG_Q, TYPE_ARG_Q], + elems: vec![type_arg_q.clone(), type_arg_q], }; let panic_op = PRELUDE .instantiate_extension_op( @@ -489,8 +492,8 @@ mod test { .unwrap(); let hugr = SimpleHugrConfig::new() - .with_ins(vec![QB_T, QB_T]) - .with_outs(vec![QB_T, QB_T]) + .with_ins(vec![qb_t(), qb_t()]) + .with_outs(vec![qb_t(), qb_t()]) .with_extensions(prelude::PRELUDE_REGISTRY.to_owned()) .finish(|mut builder| { let [q0, q1] = builder.input_wires_arr(); diff --git a/hugr-llvm/src/extension/prelude/array.rs b/hugr-llvm/src/extension/prelude/array.rs index a05cdfca7..fa33b7407 100644 --- a/hugr-llvm/src/extension/prelude/array.rs +++ b/hugr-llvm/src/extension/prelude/array.rs @@ -390,7 +390,7 @@ mod test { builder::{Dataflow, DataflowSubContainer, SubContainer}, extension::{ prelude::{ - self, array_type, option_type, ConstUsize, UnwrapBuilder as _, BOOL_T, USIZE_T, + self, array_type, bool_t, option_type, usize_t, ConstUsize, UnwrapBuilder as _, }, ExtensionRegistry, }, @@ -436,8 +436,8 @@ mod test { .finish(|mut builder| { let us1 = builder.add_load_value(ConstUsize::new(1)); let us2 = builder.add_load_value(ConstUsize::new(2)); - let arr = builder.add_new_array(USIZE_T, [us1, us2]).unwrap(); - builder.add_array_get(USIZE_T, 2, arr, us1).unwrap(); + let arr = builder.add_new_array(usize_t(), [us1, us2]).unwrap(); + builder.add_array_get(usize_t(), 2, arr, us1).unwrap(); builder.finish_with_outputs([]).unwrap() }); llvm_ctx.add_extensions(CodegenExtsBuilder::add_default_prelude_extensions); @@ -465,22 +465,22 @@ mod test { // - Gets the element at the given index // - Returns the element if the index is in bounds, otherwise 0 let hugr = SimpleHugrConfig::new() - .with_outs(USIZE_T) + .with_outs(usize_t()) .with_extensions(exec_registry()) .finish(|mut builder| { let us0 = builder.add_load_value(ConstUsize::new(0)); let us1 = builder.add_load_value(ConstUsize::new(1)); let us2 = builder.add_load_value(ConstUsize::new(2)); - let arr = builder.add_new_array(USIZE_T, [us1, us2]).unwrap(); + let arr = builder.add_new_array(usize_t(), [us1, us2]).unwrap(); let i = builder.add_load_value(ConstUsize::new(index)); - let get_r = builder.add_array_get(USIZE_T, 2, arr, i).unwrap(); + let get_r = builder.add_array_get(usize_t(), 2, arr, i).unwrap(); let r = { - let ot = option_type(USIZE_T); + let ot = option_type(usize_t()); let variants = (0..ot.num_variants()) .map(|i| ot.get_variant(i).cloned().unwrap().try_into().unwrap()) .collect_vec(); let mut builder = builder - .conditional_builder((variants, get_r), [], USIZE_T.into()) + .conditional_builder((variants, get_r), [], usize_t().into()) .unwrap(); { let failure_case = builder.case_builder(0).unwrap(); @@ -521,7 +521,7 @@ mod test { use hugr_core::extension::prelude::either_type; let int_ty = int_type(3); let hugr = SimpleHugrConfig::new() - .with_outs(USIZE_T) + .with_outs(usize_t()) .with_extensions(exec_registry()) .finish_with_exts(|mut builder, reg| { let us0 = builder.add_load_value(ConstUsize::new(0)); @@ -550,7 +550,7 @@ mod test { }) .collect_vec(); let mut builder = builder - .conditional_builder((variants, get_r), [], BOOL_T.into()) + .conditional_builder((variants, get_r), [], bool_t().into()) .unwrap(); for i in 0..2 { let mut builder = builder.case_builder(i).unwrap(); @@ -584,7 +584,7 @@ mod test { }; let r = { let mut conditional = builder - .conditional_builder(([type_row![], type_row![]], r), [], USIZE_T.into()) + .conditional_builder(([type_row![], type_row![]], r), [], usize_t().into()) .unwrap(); conditional .case_builder(0) @@ -631,7 +631,7 @@ mod test { let int_ty = int_type(3); let arr_ty = array_type(2, int_ty.clone()); let hugr = SimpleHugrConfig::new() - .with_outs(USIZE_T) + .with_outs(usize_t()) .with_extensions(exec_registry()) .finish_with_exts(|mut builder, reg| { let us0 = builder.add_load_value(ConstUsize::new(0)); @@ -653,7 +653,7 @@ mod test { r, ), [], - vec![arr_ty, BOOL_T].into(), + vec![arr_ty, bool_t()].into(), ) .unwrap(); for i in 0..2 { @@ -692,7 +692,7 @@ mod test { let r = builder.add_and(r, elem_1_ok).unwrap(); let r = { let mut conditional = builder - .conditional_builder(([type_row![], type_row![]], r), [], USIZE_T.into()) + .conditional_builder(([type_row![], type_row![]], r), [], usize_t().into()) .unwrap(); conditional .case_builder(0) diff --git a/hugr-llvm/src/lib.rs b/hugr-llvm/src/lib.rs index e7be6f571..75cb4ff58 100644 --- a/hugr-llvm/src/lib.rs +++ b/hugr-llvm/src/lib.rs @@ -80,5 +80,5 @@ pub mod test; pub use custom::{CodegenExtension, CodegenExtsBuilder}; -pub use inkwell::llvm_sys; pub use inkwell; +pub use inkwell::llvm_sys; diff --git a/hugr-llvm/src/utils/array_op_builder.rs b/hugr-llvm/src/utils/array_op_builder.rs index d41a0d05d..167584806 100644 --- a/hugr-llvm/src/utils/array_op_builder.rs +++ b/hugr-llvm/src/utils/array_op_builder.rs @@ -119,7 +119,7 @@ pub mod test { builder::{DFGBuilder, HugrBuilder}, extension::{ prelude::{ - array_type, either_type, option_type, ConstUsize, UnwrapBuilder as _, USIZE_T, + array_type, either_type, option_type, usize_t, ConstUsize, UnwrapBuilder as _, }, PRELUDE_REGISTRY, }, @@ -139,11 +139,11 @@ pub mod test { let us0 = builder.add_load_value(ConstUsize::new(0)); let us1 = builder.add_load_value(ConstUsize::new(1)); let us2 = builder.add_load_value(ConstUsize::new(2)); - let arr = builder.add_new_array(USIZE_T, [us1, us2]).unwrap(); + let arr = builder.add_new_array(usize_t(), [us1, us2]).unwrap(); let [arr] = { - let r = builder.add_array_swap(USIZE_T, 2, arr, us0, us1).unwrap(); + let r = builder.add_array_swap(usize_t(), 2, arr, us0, us1).unwrap(); let res_sum_ty = { - let array_type = array_type(2, USIZE_T); + let array_type = array_type(2, usize_t()); either_type(array_type.clone(), array_type) }; builder @@ -152,16 +152,18 @@ pub mod test { }; let [elem_0] = { - let r = builder.add_array_get(USIZE_T, 2, arr, us0).unwrap(); + let r = builder.add_array_get(usize_t(), 2, arr, us0).unwrap(); builder - .build_unwrap_sum(&PRELUDE_REGISTRY, 1, option_type(USIZE_T), r) + .build_unwrap_sum(&PRELUDE_REGISTRY, 1, option_type(usize_t()), r) .unwrap() }; let [_elem_1, arr] = { - let r = builder.add_array_set(USIZE_T, 2, arr, us1, elem_0).unwrap(); + let r = builder + .add_array_set(usize_t(), 2, arr, us1, elem_0) + .unwrap(); let res_sum_ty = { - let row = vec![USIZE_T, array_type(2, USIZE_T)]; + let row = vec![usize_t(), array_type(2, usize_t())]; either_type(row.clone(), row) }; builder @@ -170,29 +172,29 @@ pub mod test { }; let [_elem_left, arr] = { - let r = builder.add_array_pop_left(USIZE_T, 2, arr).unwrap(); + let r = builder.add_array_pop_left(usize_t(), 2, arr).unwrap(); builder .build_unwrap_sum( &PRELUDE_REGISTRY, 1, - option_type(vec![USIZE_T, array_type(1, USIZE_T)]), + option_type(vec![usize_t(), array_type(1, usize_t())]), r, ) .unwrap() }; let [_elem_right, arr] = { - let r = builder.add_array_pop_right(USIZE_T, 1, arr).unwrap(); + let r = builder.add_array_pop_right(usize_t(), 1, arr).unwrap(); builder .build_unwrap_sum( &PRELUDE_REGISTRY, 1, - option_type(vec![USIZE_T, array_type(0, USIZE_T)]), + option_type(vec![usize_t(), array_type(0, usize_t())]), r, ) .unwrap() }; - builder.add_array_discard_empty(USIZE_T, arr).unwrap(); + builder.add_array_discard_empty(usize_t(), arr).unwrap(); builder } diff --git a/hugr-llvm/src/utils/inline_constant_functions.rs b/hugr-llvm/src/utils/inline_constant_functions.rs index 638676194..aef52cd4d 100644 --- a/hugr-llvm/src/utils/inline_constant_functions.rs +++ b/hugr-llvm/src/utils/inline_constant_functions.rs @@ -94,7 +94,7 @@ mod test { Container, DFGBuilder, Dataflow, DataflowHugr, DataflowSubContainer, HugrBuilder, ModuleBuilder, }, - extension::{prelude::QB_T, PRELUDE_REGISTRY}, + extension::{prelude::qb_t, PRELUDE_REGISTRY}, ops::{CallIndirect, Const, Value}, types::Signature, Hugr, HugrView, Wire, @@ -104,7 +104,7 @@ mod test { fn build_const(go: impl FnOnce(&mut DFGBuilder) -> Wire) -> Const { Value::function({ - let mut builder = DFGBuilder::new(Signature::new_endo(QB_T)).unwrap(); + let mut builder = DFGBuilder::new(Signature::new_endo(qb_t())).unwrap(); let r = go(&mut builder); builder .finish_hugr_with_outputs([r], &PRELUDE_REGISTRY) @@ -116,7 +116,7 @@ mod test { #[test] fn simple() { - let qb_sig: Signature = Signature::new_endo(QB_T); + let qb_sig: Signature = Signature::new_endo(qb_t()); let mut hugr = { let mut builder = ModuleBuilder::new(); let const_node = builder.add_constant(build_const(|builder| { @@ -152,7 +152,7 @@ mod test { #[test] fn nested() { - let qb_sig: Signature = Signature::new_endo(QB_T); + let qb_sig: Signature = Signature::new_endo(qb_t()); let mut hugr = { let mut builder = ModuleBuilder::new(); let const_node = builder.add_constant(build_const(|builder| { diff --git a/hugr-model/tests/fixtures/model-constraints.edn b/hugr-model/tests/fixtures/model-constraints.edn index 5db6b9886..ddfbd659f 100644 --- a/hugr-model/tests/fixtures/model-constraints.edn +++ b/hugr-model/tests/fixtures/model-constraints.edn @@ -4,10 +4,10 @@ (forall ?t type) (forall ?n nat) (where (nonlinear ?t)) - [?t] [(@ array.Array ?t ?n)] + [?t] [(@ prelude.Array ?t ?n)] (ext)) (declare-func array.copy (forall ?t type) (where (nonlinear ?t)) - [(@ array.Array ?t)] [(@ array.Array ?t) (@ array.Array ?t)] (ext)) + [(@ prelude.Array ?t)] [(@ prelude.Array ?t) (@ prelude.Array ?t)] (ext)) diff --git a/hugr-passes/src/const_fold/test.rs b/hugr-passes/src/const_fold/test.rs index 473a37ac9..55d53db1c 100644 --- a/hugr-passes/src/const_fold/test.rs +++ b/hugr-passes/src/const_fold/test.rs @@ -1,7 +1,7 @@ use crate::const_fold::constant_fold_pass; use hugr_core::builder::{DFGBuilder, Dataflow, DataflowHugr}; use hugr_core::extension::prelude::{ - const_ok, sum_with_error, ConstError, ConstString, UnpackTuple, BOOL_T, ERROR_TYPE, STRING_TYPE, + bool_t, const_ok, error_type, string_type, sum_with_error, ConstError, ConstString, UnpackTuple, }; use hugr_core::extension::{ExtensionRegistry, PRELUDE}; use hugr_core::ops::Value; @@ -21,7 +21,7 @@ use hugr_core::builder::Container; use hugr_core::ops::OpType; use hugr_core::std_extensions::arithmetic::conversions::ConvertOpDef; use hugr_core::std_extensions::arithmetic::float_ops::FloatOps; -use hugr_core::std_extensions::arithmetic::float_types::{ConstF64, FLOAT64_TYPE}; +use hugr_core::std_extensions::arithmetic::float_types::{float64_type, ConstF64}; /// Check that a hugr just loads and returns a single expected constant. pub fn assert_fully_folded(h: &Hugr, expected_value: &Value) { @@ -93,7 +93,7 @@ fn test_big() { let unpack = build .add_dataflow_op( - UnpackTuple::new(type_row![FLOAT64_TYPE, FLOAT64_TYPE]), + UnpackTuple::new(vec![float64_type(), float64_type()].into()), [tup], ) .unwrap(); @@ -120,7 +120,7 @@ fn test_big() { constant_fold_pass(&mut h, ®); - let expected = const_ok(i2c(2).clone(), ERROR_TYPE); + let expected = const_ok(i2c(2).clone(), error_type()); assert_fully_folded(&h, &expected); } @@ -136,7 +136,7 @@ fn test_list_ops() -> Result<(), Box> { collections::EXTENSION.to_owned(), ]) .unwrap(); - let base_list: Value = ListValue::new(BOOL_T, [Value::false_val()]).into(); + let base_list: Value = ListValue::new(bool_t(), [Value::false_val()]).into(); let mut build = DFGBuilder::new(Signature::new( type_row![], vec![base_list.get_type().clone()], @@ -147,18 +147,21 @@ fn test_list_ops() -> Result<(), Box> { let [list, maybe_elem] = build .add_dataflow_op( - ListOp::pop.with_type(BOOL_T).to_extension_op(®).unwrap(), + ListOp::pop + .with_type(bool_t()) + .to_extension_op(®) + .unwrap(), [list], )? .outputs_arr(); - // FIXME: Unwrap the Option + // FIXME: Unwrap the Option let elem = maybe_elem; let [list] = build .add_dataflow_op( ListOp::push - .with_type(BOOL_T) + .with_type(bool_t()) .to_extension_op(®) .unwrap(), [list, elem], @@ -179,7 +182,7 @@ fn test_fold_and() { // x0, x1 := bool(true), bool(true) // x2 := and(x0, x1) // output x2 == true; - let mut build = DFGBuilder::new(noargfn(BOOL_T)).unwrap(); + let mut build = DFGBuilder::new(noargfn(bool_t())).unwrap(); let x0 = build.add_load_const(Value::true_val()); let x1 = build.add_load_const(Value::true_val()); let x2 = build.add_dataflow_op(LogicOp::And, [x0, x1]).unwrap(); @@ -197,7 +200,7 @@ fn test_fold_or() { // x0, x1 := bool(true), bool(false) // x2 := or(x0, x1) // output x2 == true; - let mut build = DFGBuilder::new(noargfn(BOOL_T)).unwrap(); + let mut build = DFGBuilder::new(noargfn(bool_t())).unwrap(); let x0 = build.add_load_const(Value::true_val()); let x1 = build.add_load_const(Value::false_val()); let x2 = build.add_dataflow_op(LogicOp::Or, [x0, x1]).unwrap(); @@ -215,7 +218,7 @@ fn test_fold_not() { // x0 := bool(true) // x1 := not(x0) // output x1 == false; - let mut build = DFGBuilder::new(noargfn(BOOL_T)).unwrap(); + let mut build = DFGBuilder::new(noargfn(bool_t())).unwrap(); let x0 = build.add_load_const(Value::true_val()); let x1 = build.add_dataflow_op(LogicOp::Not, [x0]).unwrap(); let reg = @@ -238,7 +241,7 @@ fn orphan_output() { // with no outputs. use hugr_core::ops::handle::NodeHandle; - let mut build = DFGBuilder::new(noargfn(vec![BOOL_T])).unwrap(); + let mut build = DFGBuilder::new(noargfn(vec![bool_t()])).unwrap(); let true_wire = build.add_load_value(Value::true_val()); // this Not will be manually replaced let orig_not = build.add_dataflow_op(LogicOp::Not, [true_wire]).unwrap(); @@ -275,7 +278,7 @@ fn test_folding_pass_issue_996() { // x6 := flt(x0, x5) // false // x7 := or(x4, x6) // true // output x7 - let mut build = DFGBuilder::new(noargfn(vec![BOOL_T])).unwrap(); + let mut build = DFGBuilder::new(noargfn(vec![bool_t()])).unwrap(); let x0 = build.add_load_const(Value::extension(ConstF64::new(3.0))); let x1 = build.add_load_const(Value::extension(ConstF64::new(4.0))); let x2 = build.add_dataflow_op(FloatOps::fne, [x0, x1]).unwrap(); @@ -309,7 +312,7 @@ fn test_const_fold_to_nonfinite() { .unwrap(); // HUGR computing 1.0 / 1.0 - let mut build = DFGBuilder::new(noargfn(vec![FLOAT64_TYPE])).unwrap(); + let mut build = DFGBuilder::new(noargfn(vec![float64_type()])).unwrap(); let x0 = build.add_load_const(Value::extension(ConstF64::new(1.0))); let x1 = build.add_load_const(Value::extension(ConstF64::new(1.0))); let x2 = build.add_dataflow_op(FloatOps::fdiv, [x0, x1]).unwrap(); @@ -321,7 +324,7 @@ fn test_const_fold_to_nonfinite() { assert_eq!(h0.node_count(), 5); // HUGR computing 1.0 / 0.0 - let mut build = DFGBuilder::new(noargfn(vec![FLOAT64_TYPE])).unwrap(); + let mut build = DFGBuilder::new(noargfn(vec![float64_type()])).unwrap(); let x0 = build.add_load_const(Value::extension(ConstF64::new(1.0))); let x1 = build.add_load_const(Value::extension(ConstF64::new(0.0))); let x2 = build.add_dataflow_op(FloatOps::fdiv, [x0, x1]).unwrap(); @@ -430,7 +433,7 @@ fn test_fold_inarrow, E: std::fmt::Debug>( }; } let expected = if succeeds { - const_ok(mk_const(to_log_width, val).unwrap().into(), ERROR_TYPE) + const_ok(mk_const(to_log_width, val).unwrap().into(), error_type()) } else { INARROW_ERROR_VALUE.clone().as_either(elem_type) }; @@ -444,7 +447,7 @@ fn test_fold_itobool() { // x0 := int_u<0>(1); // x1 := itobool(x0); // output x1 == true; - let mut build = DFGBuilder::new(noargfn(vec![BOOL_T])).unwrap(); + let mut build = DFGBuilder::new(noargfn(vec![bool_t()])).unwrap(); let x0 = build.add_load_const(Value::extension(ConstInt::new_u(0, 1).unwrap())); let x1 = build .add_dataflow_op(ConvertOpDef::itobool.without_log_width(), [x0]) @@ -489,7 +492,7 @@ fn test_fold_ieq() { // x0, x1 := int_s<3>(-1), int_u<3>(255) // x2 := ieq(x0, x1) // output x2 == true; - let mut build = DFGBuilder::new(noargfn(vec![BOOL_T])).unwrap(); + let mut build = DFGBuilder::new(noargfn(vec![bool_t()])).unwrap(); let x0 = build.add_load_const(Value::extension(ConstInt::new_s(3, -1).unwrap())); let x1 = build.add_load_const(Value::extension(ConstInt::new_u(3, 255).unwrap())); let x2 = build @@ -512,7 +515,7 @@ fn test_fold_ine() { // x0, x1 := int_u<5>(3), int_u<5>(4) // x2 := ine(x0, x1) // output x2 == true; - let mut build = DFGBuilder::new(noargfn(vec![BOOL_T])).unwrap(); + let mut build = DFGBuilder::new(noargfn(vec![bool_t()])).unwrap(); let x0 = build.add_load_const(Value::extension(ConstInt::new_u(5, 3).unwrap())); let x1 = build.add_load_const(Value::extension(ConstInt::new_u(5, 4).unwrap())); let x2 = build @@ -535,7 +538,7 @@ fn test_fold_ilt_u() { // x0, x1 := int_u<5>(3), int_u<5>(4) // x2 := ilt_u(x0, x1) // output x2 == true; - let mut build = DFGBuilder::new(noargfn(vec![BOOL_T])).unwrap(); + let mut build = DFGBuilder::new(noargfn(vec![bool_t()])).unwrap(); let x0 = build.add_load_const(Value::extension(ConstInt::new_u(5, 3).unwrap())); let x1 = build.add_load_const(Value::extension(ConstInt::new_u(5, 4).unwrap())); let x2 = build @@ -558,7 +561,7 @@ fn test_fold_ilt_s() { // x0, x1 := int_s<5>(3), int_s<5>(-4) // x2 := ilt_s(x0, x1) // output x2 == false; - let mut build = DFGBuilder::new(noargfn(vec![BOOL_T])).unwrap(); + let mut build = DFGBuilder::new(noargfn(vec![bool_t()])).unwrap(); let x0 = build.add_load_const(Value::extension(ConstInt::new_s(5, 3).unwrap())); let x1 = build.add_load_const(Value::extension(ConstInt::new_s(5, -4).unwrap())); let x2 = build @@ -581,7 +584,7 @@ fn test_fold_igt_u() { // x0, x1 := int_u<5>(3), int_u<5>(4) // x2 := ilt_u(x0, x1) // output x2 == false; - let mut build = DFGBuilder::new(noargfn(vec![BOOL_T])).unwrap(); + let mut build = DFGBuilder::new(noargfn(vec![bool_t()])).unwrap(); let x0 = build.add_load_const(Value::extension(ConstInt::new_u(5, 3).unwrap())); let x1 = build.add_load_const(Value::extension(ConstInt::new_u(5, 4).unwrap())); let x2 = build @@ -604,7 +607,7 @@ fn test_fold_igt_s() { // x0, x1 := int_s<5>(3), int_s<5>(-4) // x2 := ilt_s(x0, x1) // output x2 == true; - let mut build = DFGBuilder::new(noargfn(vec![BOOL_T])).unwrap(); + let mut build = DFGBuilder::new(noargfn(vec![bool_t()])).unwrap(); let x0 = build.add_load_const(Value::extension(ConstInt::new_s(5, 3).unwrap())); let x1 = build.add_load_const(Value::extension(ConstInt::new_s(5, -4).unwrap())); let x2 = build @@ -627,7 +630,7 @@ fn test_fold_ile_u() { // x0, x1 := int_u<5>(3), int_u<5>(3) // x2 := ile_u(x0, x1) // output x2 == true; - let mut build = DFGBuilder::new(noargfn(vec![BOOL_T])).unwrap(); + let mut build = DFGBuilder::new(noargfn(vec![bool_t()])).unwrap(); let x0 = build.add_load_const(Value::extension(ConstInt::new_u(5, 3).unwrap())); let x1 = build.add_load_const(Value::extension(ConstInt::new_u(5, 3).unwrap())); let x2 = build @@ -650,7 +653,7 @@ fn test_fold_ile_s() { // x0, x1 := int_s<5>(-4), int_s<5>(-4) // x2 := ile_s(x0, x1) // output x2 == true; - let mut build = DFGBuilder::new(noargfn(vec![BOOL_T])).unwrap(); + let mut build = DFGBuilder::new(noargfn(vec![bool_t()])).unwrap(); let x0 = build.add_load_const(Value::extension(ConstInt::new_s(5, -4).unwrap())); let x1 = build.add_load_const(Value::extension(ConstInt::new_s(5, -4).unwrap())); let x2 = build @@ -673,7 +676,7 @@ fn test_fold_ige_u() { // x0, x1 := int_u<5>(3), int_u<5>(4) // x2 := ilt_u(x0, x1) // output x2 == false; - let mut build = DFGBuilder::new(noargfn(vec![BOOL_T])).unwrap(); + let mut build = DFGBuilder::new(noargfn(vec![bool_t()])).unwrap(); let x0 = build.add_load_const(Value::extension(ConstInt::new_u(5, 3).unwrap())); let x1 = build.add_load_const(Value::extension(ConstInt::new_u(5, 4).unwrap())); let x2 = build @@ -696,7 +699,7 @@ fn test_fold_ige_s() { // x0, x1 := int_s<5>(3), int_s<5>(-4) // x2 := ilt_s(x0, x1) // output x2 == true; - let mut build = DFGBuilder::new(noargfn(vec![BOOL_T])).unwrap(); + let mut build = DFGBuilder::new(noargfn(vec![bool_t()])).unwrap(); let x0 = build.add_load_const(Value::extension(ConstInt::new_s(5, 3).unwrap())); let x1 = build.add_load_const(Value::extension(ConstInt::new_s(5, -4).unwrap())); let x2 = build @@ -1429,7 +1432,7 @@ fn test_fold_itostring_u() { // x0 := int_u<5>(17); // x1 := itostring_u(x0); // output x2 := "17"; - let mut build = DFGBuilder::new(noargfn(vec![STRING_TYPE])).unwrap(); + let mut build = DFGBuilder::new(noargfn(vec![string_type()])).unwrap(); let x0 = build.add_load_const(Value::extension(ConstInt::new_u(5, 17).unwrap())); let x1 = build .add_dataflow_op(ConvertOpDef::itostring_u.with_log_width(5), [x0]) @@ -1451,7 +1454,7 @@ fn test_fold_itostring_s() { // x0 := int_s<5>(-17); // x1 := itostring_s(x0); // output x2 := "-17"; - let mut build = DFGBuilder::new(noargfn(vec![STRING_TYPE])).unwrap(); + let mut build = DFGBuilder::new(noargfn(vec![string_type()])).unwrap(); let x0 = build.add_load_const(Value::extension(ConstInt::new_s(5, -17).unwrap())); let x1 = build .add_dataflow_op(ConvertOpDef::itostring_s.with_log_width(5), [x0]) @@ -1480,7 +1483,7 @@ fn test_fold_int_ops() { // x6 := ilt_s(x0, x5) // false // x7 := or(x4, x6) // true // output x7 - let mut build = DFGBuilder::new(noargfn(vec![BOOL_T])).unwrap(); + let mut build = DFGBuilder::new(noargfn(vec![bool_t()])).unwrap(); let x0 = build.add_load_const(Value::extension(ConstInt::new_u(5, 3).unwrap())); let x1 = build.add_load_const(Value::extension(ConstInt::new_u(5, 4).unwrap())); let x2 = build diff --git a/hugr-passes/src/lower.rs b/hugr-passes/src/lower.rs index b799638fc..3c3d8a40c 100644 --- a/hugr-passes/src/lower.rs +++ b/hugr-passes/src/lower.rs @@ -80,7 +80,7 @@ pub fn lower_ops( mod test { use hugr_core::{ builder::{DFGBuilder, Dataflow, DataflowHugr}, - extension::prelude::{Noop, BOOL_T}, + extension::prelude::{bool_t, Noop}, std_extensions::logic::LogicOp, types::Signature, HugrView, @@ -91,9 +91,9 @@ mod test { #[fixture] fn noop_hugr() -> Hugr { - let mut b = DFGBuilder::new(Signature::new_endo(BOOL_T).with_prelude()).unwrap(); + let mut b = DFGBuilder::new(Signature::new_endo(bool_t()).with_prelude()).unwrap(); let out = b - .add_dataflow_op(Noop::new(BOOL_T), [b.input_wires().next().unwrap()]) + .add_dataflow_op(Noop::new(bool_t()), [b.input_wires().next().unwrap()]) .unwrap() .out_wire(0); b.finish_prelude_hugr_with_outputs([out]).unwrap() @@ -101,7 +101,7 @@ mod test { #[fixture] fn identity_hugr() -> Hugr { - let b = DFGBuilder::new(Signature::new_endo(BOOL_T)).unwrap(); + let b = DFGBuilder::new(Signature::new_endo(bool_t())).unwrap(); let out = b.input_wires().next().unwrap(); b.finish_prelude_hugr_with_outputs([out]).unwrap() } @@ -110,7 +110,7 @@ mod test { fn test_replace(noop_hugr: Hugr) { let mut h = noop_hugr; let mut replaced = replace_many_ops(&mut h, |op| { - let noop = Noop::new(BOOL_T); + let noop = Noop::new(bool_t()); if op.cast() == Some(noop) { Some(LogicOp::Not) } else { @@ -121,7 +121,7 @@ mod test { assert_eq!(replaced.len(), 1); let (n, op) = replaced.remove(0); - assert_eq!(op, Noop::new(BOOL_T).into()); + assert_eq!(op, Noop::new(bool_t()).into()); assert_eq!(h.get_optype(n), &LogicOp::Not.into()); } @@ -130,7 +130,7 @@ mod test { let mut h = noop_hugr; let lowered = lower_ops(&mut h, |op| { - let noop = Noop::new(BOOL_T); + let noop = Noop::new(bool_t()); if op.cast() == Some(noop) { Some(identity_hugr.clone()) } else { diff --git a/hugr-passes/src/merge_bbs.rs b/hugr-passes/src/merge_bbs.rs index 3ac3dacb7..1acda2ba7 100644 --- a/hugr-passes/src/merge_bbs.rs +++ b/hugr-passes/src/merge_bbs.rs @@ -164,7 +164,7 @@ mod test { use rstest::rstest; use hugr_core::builder::{endo_sig, inout_sig, CFGBuilder, DFGWrapper, Dataflow, HugrBuilder}; - use hugr_core::extension::prelude::{ConstUsize, PRELUDE_ID, QB_T, USIZE_T}; + use hugr_core::extension::prelude::{qb_t, usize_t, ConstUsize, PRELUDE_ID}; use hugr_core::extension::{ExtensionRegistry, PRELUDE, PRELUDE_REGISTRY}; use hugr_core::hugr::views::sibling::SiblingMut; use hugr_core::ops::constant::Value; @@ -188,11 +188,8 @@ mod test { "Test".into(), String::new(), Signature::new( - type_row![QB_T, USIZE_T], - TypeRow::from(vec![Type::new_sum(vec![ - type_row![QB_T], - type_row![USIZE_T], - ])]), + vec![qb_t(), usize_t()], + TypeRow::from(vec![Type::new_sum(vec![vec![qb_t()], vec![usize_t()]])]), ), extension_ref, ) @@ -205,7 +202,7 @@ mod test { let lc = b.add_load_value(Value::unary_unit_sum()); let lift = b .add_dataflow_op( - Lift::new(type_row![Type::new_unit_sum(1)], PRELUDE_ID), + Lift::new(vec![Type::new_unit_sum(1)].into(), PRELUDE_ID), [lc], ) .unwrap(); @@ -230,14 +227,14 @@ mod test { */ use hugr_core::extension::prelude::Noop; - let loop_variants = type_row![QB_T]; - let exit_types = type_row![USIZE_T]; + let loop_variants: TypeRow = vec![qb_t()].into(); + let exit_types: TypeRow = vec![usize_t()].into(); let e = extension(); let tst_op = e.instantiate_extension_op("Test", [], &PRELUDE_REGISTRY)?; let reg = ExtensionRegistry::try_new([PRELUDE.clone(), e])?; let mut h = CFGBuilder::new(inout_sig(loop_variants.clone(), exit_types.clone()))?; let mut no_b1 = h.simple_entry_builder_exts(loop_variants.clone(), 1, PRELUDE_ID)?; - let n = no_b1.add_dataflow_op(Noop::new(QB_T), no_b1.input_wires())?; + let n = no_b1.add_dataflow_op(Noop::new(qb_t()), no_b1.input_wires())?; let br = lifted_unary_unit_sum(&mut no_b1); let no_b1 = no_b1.finish_with_outputs(br, n.outputs())?; let mut test_block = h.block_builder( @@ -255,7 +252,7 @@ mod test { no_b1 } else { let mut no_b2 = h.simple_block_builder(endo_sig(loop_variants), 1)?; - let n = no_b2.add_dataflow_op(Noop::new(QB_T), no_b2.input_wires())?; + let n = no_b2.add_dataflow_op(Noop::new(qb_t()), no_b2.input_wires())?; let br = lifted_unary_unit_sum(&mut no_b2); let nid = no_b2.finish_with_outputs(br, n.outputs())?; h.branch(&nid, 0, &no_b1)?; @@ -331,24 +328,24 @@ mod test { .into_owned() .try_into() .unwrap(); - let mut h = CFGBuilder::new(inout_sig(QB_T, res_t.clone()))?; - let mut bb1 = h.simple_entry_builder(type_row![USIZE_T, QB_T], 1)?; + let mut h = CFGBuilder::new(inout_sig(qb_t(), res_t.clone()))?; + let mut bb1 = h.simple_entry_builder(vec![usize_t(), qb_t()].into(), 1)?; let [inw] = bb1.input_wires_arr(); let load_cst = bb1.add_load_value(ConstUsize::new(1)); let pred = lifted_unary_unit_sum(&mut bb1); let bb1 = bb1.finish_with_outputs(pred, [load_cst, inw])?; let mut bb2 = h.block_builder( - type_row![USIZE_T, QB_T], + vec![usize_t(), qb_t()].into(), vec![type_row![]], - type_row![QB_T, USIZE_T], + vec![qb_t(), usize_t()].into(), )?; let [u, q] = bb2.input_wires_arr(); let pred = lifted_unary_unit_sum(&mut bb2); let bb2 = bb2.finish_with_outputs(pred, [q, u])?; let mut bb3 = h.block_builder( - type_row![QB_T, USIZE_T], + vec![qb_t(), usize_t()].into(), vec![type_row![]], res_t.clone().into(), )?; @@ -381,7 +378,10 @@ mod test { let [other_input] = tst_inputs.try_into().unwrap(); assert_eq!( h.get_optype(other_input), - &(LoadConstant { datatype: USIZE_T }.into()) + &(LoadConstant { + datatype: usize_t() + } + .into()) ); Ok(()) } diff --git a/hugr-passes/src/nest_cfgs.rs b/hugr-passes/src/nest_cfgs.rs index fa7106432..b8091c7af 100644 --- a/hugr-passes/src/nest_cfgs.rs +++ b/hugr-passes/src/nest_cfgs.rs @@ -571,16 +571,14 @@ pub(crate) mod test { endo_sig, BuildError, CFGBuilder, Container, DataflowSubContainer, HugrBuilder, }; use hugr_core::extension::PRELUDE_REGISTRY; - use hugr_core::extension::{prelude::USIZE_T, ExtensionSet}; + use hugr_core::extension::{prelude::usize_t, ExtensionSet}; use hugr_core::hugr::rewrite::insert_identity::{IdentityInsertion, IdentityInsertionError}; use hugr_core::hugr::views::RootChecked; use hugr_core::ops::handle::{ConstID, NodeHandle}; use hugr_core::ops::Value; - use hugr_core::type_row; - use hugr_core::types::{EdgeKind, Signature, Type}; + use hugr_core::types::{EdgeKind, Signature}; use hugr_core::utils::depth; - const NAT: Type = USIZE_T; pub fn group_by(h: HashMap) -> HashSet> { let mut res = HashMap::new(); @@ -601,23 +599,27 @@ pub(crate) mod test { // /-> left --\ // entry -> split > merge -> head -> tail -> exit // \-> right -/ \-<--<-/ - let mut cfg_builder = CFGBuilder::new(Signature::new_endo(NAT))?; + let mut cfg_builder = CFGBuilder::new(Signature::new_endo(usize_t()))?; let pred_const = cfg_builder.add_constant(Value::unit_sum(0, 2).expect("0 < 2")); let const_unit = cfg_builder.add_constant(Value::unary_unit_sum()); let entry = n_identity( - cfg_builder.simple_entry_builder_exts(type_row![NAT], 1, ExtensionSet::new())?, + cfg_builder.simple_entry_builder_exts( + vec![usize_t()].into(), + 1, + ExtensionSet::new(), + )?, &const_unit, )?; let (split, merge) = build_if_then_else_merge(&mut cfg_builder, &pred_const, &const_unit)?; cfg_builder.branch(&entry, 0, &split)?; let head = n_identity( - cfg_builder.simple_block_builder(endo_sig(NAT), 1)?, + cfg_builder.simple_block_builder(endo_sig(usize_t()), 1)?, &const_unit, )?; let tail = n_identity( - cfg_builder.simple_block_builder(endo_sig(NAT), 2)?, + cfg_builder.simple_block_builder(endo_sig(usize_t()), 2)?, &pred_const, )?; cfg_builder.branch(&tail, 1, &head)?; @@ -844,7 +846,10 @@ pub(crate) mod test { const_pred: &ConstID, unit_const: &ConstID, ) -> Result<(BasicBlockID, BasicBlockID), BuildError> { - let split = n_identity(cfg.simple_block_builder(endo_sig(NAT), 2)?, const_pred)?; + let split = n_identity( + cfg.simple_block_builder(endo_sig(usize_t()), 2)?, + const_pred, + )?; let merge = build_then_else_merge_from_if(cfg, unit_const, split)?; Ok((split, merge)) } @@ -854,9 +859,18 @@ pub(crate) mod test { unit_const: &ConstID, split: BasicBlockID, ) -> Result { - let merge = n_identity(cfg.simple_block_builder(endo_sig(NAT), 1)?, unit_const)?; - let left = n_identity(cfg.simple_block_builder(endo_sig(NAT), 1)?, unit_const)?; - let right = n_identity(cfg.simple_block_builder(endo_sig(NAT), 1)?, unit_const)?; + let merge = n_identity( + cfg.simple_block_builder(endo_sig(usize_t()), 1)?, + unit_const, + )?; + let left = n_identity( + cfg.simple_block_builder(endo_sig(usize_t()), 1)?, + unit_const, + )?; + let right = n_identity( + cfg.simple_block_builder(endo_sig(usize_t()), 1)?, + unit_const, + )?; cfg.branch(&split, 0, &left)?; cfg.branch(&split, 1, &right)?; cfg.branch(&left, 0, &merge)?; @@ -869,18 +883,18 @@ pub(crate) mod test { // \-> right -/ \-<--<-/ // Result is Hugr plus merge and tail blocks fn build_cond_then_loop_cfg() -> Result<(Hugr, BasicBlockID, BasicBlockID), BuildError> { - let mut cfg_builder = CFGBuilder::new(Signature::new_endo(NAT))?; + let mut cfg_builder = CFGBuilder::new(Signature::new_endo(usize_t()))?; let pred_const = cfg_builder.add_constant(Value::unit_sum(0, 2).expect("0 < 2")); let const_unit = cfg_builder.add_constant(Value::unary_unit_sum()); let entry = n_identity( - cfg_builder.simple_entry_builder(type_row![NAT], 2)?, + cfg_builder.simple_entry_builder(vec![usize_t()].into(), 2)?, &pred_const, )?; let merge = build_then_else_merge_from_if(&mut cfg_builder, &const_unit, entry)?; // The merge block is also the loop header (so it merges three incoming control-flow edges) let tail = n_identity( - cfg_builder.simple_block_builder(endo_sig(NAT), 2)?, + cfg_builder.simple_block_builder(endo_sig(usize_t()), 2)?, &pred_const, )?; cfg_builder.branch(&tail, 1, &merge)?; @@ -896,7 +910,7 @@ pub(crate) mod test { pub(crate) fn build_conditional_in_loop_cfg( separate_headers: bool, ) -> Result<(Hugr, BasicBlockID, BasicBlockID), BuildError> { - let mut cfg_builder = CFGBuilder::new(Signature::new_endo(NAT))?; + let mut cfg_builder = CFGBuilder::new(Signature::new_endo(usize_t()))?; let (head, tail) = build_conditional_in_loop(&mut cfg_builder, separate_headers)?; let h = cfg_builder.finish_prelude_hugr()?; Ok((h, head, tail)) @@ -910,14 +924,14 @@ pub(crate) mod test { let const_unit = cfg_builder.add_constant(Value::unary_unit_sum()); let entry = n_identity( - cfg_builder.simple_entry_builder(type_row![NAT], 1)?, + cfg_builder.simple_entry_builder(vec![usize_t()].into(), 1)?, &const_unit, )?; let (split, merge) = build_if_then_else_merge(cfg_builder, &pred_const, &const_unit)?; let head = if separate_headers { let head = n_identity( - cfg_builder.simple_block_builder(endo_sig(NAT), 1)?, + cfg_builder.simple_block_builder(endo_sig(usize_t()), 1)?, &const_unit, )?; cfg_builder.branch(&head, 0, &split)?; @@ -927,7 +941,7 @@ pub(crate) mod test { split }; let tail = n_identity( - cfg_builder.simple_block_builder(endo_sig(NAT), 2)?, + cfg_builder.simple_block_builder(endo_sig(usize_t()), 2)?, &pred_const, )?; cfg_builder.branch(&tail, 1, &head)?; diff --git a/hugr-passes/src/non_local.rs b/hugr-passes/src/non_local.rs index 347e5be27..0b23709a9 100644 --- a/hugr-passes/src/non_local.rs +++ b/hugr-passes/src/non_local.rs @@ -43,7 +43,7 @@ mod test { use hugr_core::{ builder::{DFGBuilder, Dataflow, DataflowHugr, DataflowSubContainer}, extension::{ - prelude::{Noop, BOOL_T}, + prelude::{bool_t, Noop}, EMPTY_REG, }, ops::handle::NodeHandle, @@ -56,10 +56,11 @@ mod test { #[test] fn ensures_no_nonlocal_edges() { let hugr = { - let mut builder = DFGBuilder::new(Signature::new_endo(BOOL_T).with_prelude()).unwrap(); + let mut builder = + DFGBuilder::new(Signature::new_endo(bool_t()).with_prelude()).unwrap(); let [in_w] = builder.input_wires_arr(); let [out_w] = builder - .add_dataflow_op(Noop::new(BOOL_T), [in_w]) + .add_dataflow_op(Noop::new(bool_t()), [in_w]) .unwrap() .outputs_arr(); builder @@ -72,14 +73,15 @@ mod test { #[test] fn find_nonlocal_edges() { let (hugr, edge) = { - let mut builder = DFGBuilder::new(Signature::new_endo(BOOL_T).with_prelude()).unwrap(); + let mut builder = + DFGBuilder::new(Signature::new_endo(bool_t()).with_prelude()).unwrap(); let [in_w] = builder.input_wires_arr(); let ([out_w], edge) = { let mut dfg_builder = builder - .dfg_builder(Signature::new(type_row![], BOOL_T).with_prelude(), []) + .dfg_builder(Signature::new(type_row![], bool_t()).with_prelude(), []) .unwrap(); let noop = dfg_builder - .add_dataflow_op(Noop::new(BOOL_T), [in_w]) + .add_dataflow_op(Noop::new(bool_t()), [in_w]) .unwrap(); let noop_edge = (noop.node(), IncomingPort::from(0)); ( diff --git a/hugr/benches/benchmarks/hugr/examples.rs b/hugr/benches/benchmarks/hugr/examples.rs index 48a336d2d..9cc64f610 100644 --- a/hugr/benches/benchmarks/hugr/examples.rs +++ b/hugr/benches/benchmarks/hugr/examples.rs @@ -6,18 +6,17 @@ use hugr::builder::{ BuildError, CFGBuilder, Container, DFGBuilder, Dataflow, DataflowHugr, DataflowSubContainer, HugrBuilder, ModuleBuilder, }; -use hugr::extension::prelude::{BOOL_T, QB_T, USIZE_T}; +use hugr::extension::prelude::{bool_t, qb_t, usize_t}; use hugr::extension::PRELUDE_REGISTRY; use hugr::ops::OpName; use hugr::std_extensions::arithmetic::float_ops::FLOAT_OPS_REGISTRY; -use hugr::std_extensions::arithmetic::float_types::FLOAT64_TYPE; +use hugr::std_extensions::arithmetic::float_types::float64_type; use hugr::types::Signature; use hugr::{type_row, Extension, Hugr, Node}; use lazy_static::lazy_static; pub fn simple_dfg_hugr() -> Hugr { - let dfg_builder = - DFGBuilder::new(Signature::new(type_row![BOOL_T], type_row![BOOL_T])).unwrap(); + let dfg_builder = DFGBuilder::new(Signature::new(vec![bool_t()], vec![bool_t()])).unwrap(); let [i1] = dfg_builder.input_wires_arr(); dfg_builder.finish_prelude_hugr_with_outputs([i1]).unwrap() } @@ -25,7 +24,7 @@ pub fn simple_dfg_hugr() -> Hugr { pub fn simple_cfg_builder + AsRef>( cfg_builder: &mut CFGBuilder, ) -> Result<(), BuildError> { - let sum2_variants = vec![type_row![USIZE_T], type_row![USIZE_T]]; + let sum2_variants = vec![vec![usize_t()].into(), vec![usize_t()].into()]; let mut entry_b = cfg_builder.entry_builder(sum2_variants.clone(), type_row![])?; let entry = { let [inw] = entry_b.input_wires_arr(); @@ -33,8 +32,8 @@ pub fn simple_cfg_builder + AsRef>( let sum = entry_b.make_sum(1, sum2_variants, [inw])?; entry_b.finish_with_outputs(sum, [])? }; - let mut middle_b = cfg_builder - .simple_block_builder(Signature::new(type_row![USIZE_T], type_row![USIZE_T]), 1)?; + let mut middle_b = + cfg_builder.simple_block_builder(Signature::new(vec![usize_t()], vec![usize_t()]), 1)?; let middle = { let c = middle_b.add_load_const(hugr::ops::Value::unary_unit_sum()); let [inw] = middle_b.input_wires_arr(); @@ -49,7 +48,7 @@ pub fn simple_cfg_builder + AsRef>( pub fn simple_cfg_hugr() -> Hugr { let mut cfg_builder = - CFGBuilder::new(Signature::new(type_row![USIZE_T], type_row![USIZE_T])).unwrap(); + CFGBuilder::new(Signature::new(vec![usize_t()], vec![usize_t()])).unwrap(); simple_cfg_builder(&mut cfg_builder).unwrap(); cfg_builder.finish_prelude_hugr().unwrap() } @@ -63,14 +62,14 @@ lazy_static! { ext.add_op( OpName::new_inline("H"), "".into(), - Signature::new_endo(QB_T), + Signature::new_endo(qb_t()), extension_ref, ) .unwrap(); ext.add_op( OpName::new_inline("Rz"), "".into(), - Signature::new(type_row![QB_T, FLOAT64_TYPE], type_row![QB_T]), + Signature::new(vec![qb_t(), float64_type()], vec![qb_t()]), extension_ref, ) .unwrap(); @@ -78,7 +77,7 @@ lazy_static! { ext.add_op( OpName::new_inline("CX"), "".into(), - Signature::new_endo(type_row![QB_T, QB_T]), + Signature::new_endo(vec![qb_t(), qb_t()]), extension_ref, ) .unwrap(); @@ -106,7 +105,7 @@ pub fn circuit(layers: usize) -> (Hugr, Vec) { // .instantiate_extension_op("Rz", [], &FLOAT_OPS_REGISTRY) // .unwrap(); let signature = - Signature::new_endo(type_row![QB_T, QB_T]).with_extension_delta(QUANTUM_EXT.name().clone()); + Signature::new_endo(vec![qb_t(), qb_t()]).with_extension_delta(QUANTUM_EXT.name().clone()); let mut module_builder = ModuleBuilder::new(); let mut f_build = module_builder.define_function("main", signature).unwrap(); diff --git a/hugr/benches/benchmarks/types.rs b/hugr/benches/benchmarks/types.rs index a109a05d8..07cbdb24d 100644 --- a/hugr/benches/benchmarks/types.rs +++ b/hugr/benches/benchmarks/types.rs @@ -1,6 +1,6 @@ // Required for black_box uses #![allow(clippy::unit_arg)] -use hugr::extension::prelude::{QB_T, USIZE_T}; +use hugr::extension::prelude::{qb_t, usize_t}; use hugr::ops::AliasDecl; use hugr::types::{Signature, Type, TypeBound}; @@ -8,8 +8,8 @@ use criterion::{black_box, criterion_group, AxisScale, Criterion, PlotConfigurat /// Construct a complex type. fn make_complex_type() -> Type { - let qb = QB_T; - let int = USIZE_T; + let qb = qb_t(); + let int = usize_t(); let q_register = Type::new_tuple(vec![qb; 8]); let b_register = Type::new_tuple(vec![int; 8]); let q_alias = Type::new_alias(AliasDecl::new("QReg", TypeBound::Any)); diff --git a/hugr/src/lib.rs b/hugr/src/lib.rs index d23063dfa..b5899c7ec 100644 --- a/hugr/src/lib.rs +++ b/hugr/src/lib.rs @@ -28,17 +28,17 @@ //! a simple quantum extension and then use the [[builder::DFGBuilder]] as follows: //! ``` //! use hugr::builder::{BuildError, DFGBuilder, Dataflow, DataflowHugr, inout_sig}; -//! use hugr::extension::prelude::{BOOL_T, QB_T}; +//! use hugr::extension::prelude::{bool_t, qb_t}; //! use hugr::hugr::Hugr; //! use hugr::type_row; //! use hugr::types::FuncValueType; //! -//! // The type of qubits, `QB_T` is in the prelude but, by default, no gateset +//! // The type of qubits, `qb_t()` is in the prelude but, by default, no gateset //! // is defined. This module provides Hadamard and CX gates. //! mod mini_quantum_extension { //! use hugr::{ //! extension::{ -//! prelude::{BOOL_T, QB_T}, +//! prelude::{bool_t, qb_t}, //! ExtensionId, ExtensionRegistry, PRELUDE, Version, //! }, //! ops::{ExtensionOp, OpName}, @@ -51,11 +51,11 @@ //! use lazy_static::lazy_static; //! //! fn one_qb_func() -> PolyFuncTypeRV { -//! FuncValueType::new_endo(type_row![QB_T]).into() +//! FuncValueType::new_endo(vec![qb_t()]).into() //! } //! //! fn two_qb_func() -> PolyFuncTypeRV { -//! FuncValueType::new_endo(type_row![QB_T, QB_T]).into() +//! FuncValueType::new_endo(vec![qb_t(), qb_t()]).into() //! } //! /// The extension identifier. //! pub const EXTENSION_ID: ExtensionId = ExtensionId::new_unchecked("mini.quantum"); @@ -71,7 +71,7 @@ //! ext.add_op( //! OpName::new_inline("Measure"), //! "Measure a qubit, returning the qubit and the measurement result.".into(), -//! FuncValueType::new(type_row![QB_T], type_row![QB_T, BOOL_T]), +//! FuncValueType::new(vec![qb_t()], vec![qb_t(), bool_t()]), //! extension_ref, //! ) //! .unwrap(); @@ -113,8 +113,8 @@ //! // c: ╚═ //! fn make_dfg_hugr() -> Result { //! let mut dfg_builder = DFGBuilder::new(inout_sig( -//! type_row![QB_T, QB_T], -//! type_row![QB_T, QB_T, BOOL_T], +//! vec![qb_t(), qb_t()], +//! vec![qb_t(), qb_t(), bool_t()], //! ))?; //! let [wire0, wire1] = dfg_builder.input_wires_arr(); //! let h0 = dfg_builder.add_dataflow_op(h_gate(), vec![wire0])?; diff --git a/justfile b/justfile index 78267180a..ed8c1b73c 100644 --- a/justfile +++ b/justfile @@ -32,7 +32,7 @@ fix language="[rust|python]": (_run_lang language \ # Format the code. format language="[rust|python]": (_run_lang language \ - "cargo fmt" \ + "cargo fmt --all" \ "uv run ruff format" ) diff --git a/uv.lock b/uv.lock index 9dc359a56..7f8bd6af4 100644 --- a/uv.lock +++ b/uv.lock @@ -280,7 +280,7 @@ docs = [ [package.metadata] requires-dist = [ { name = "graphviz", specifier = ">=0.20.3" }, - { name = "pydantic", specifier = ">=2.8,<2.10" }, + { name = "pydantic", specifier = ">=2.8,<2.11" }, { name = "pydantic-extra-types", specifier = ">=2.9.0" }, { name = "semver", specifier = ">=3.0.2" }, { name = "sphinx", marker = "extra == 'docs'", specifier = ">=8.0.2,<9.0.0" },