From b5ddc8fc4983505ee28926c8b5f14a557ad4bef2 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sun, 26 May 2024 09:21:09 +0100 Subject: [PATCH 001/115] FunctionType defaults true, false->Signature, PFT::new takes impl Into, update Dataflow/Ops etc. --- hugr/src/builder.rs | 4 +- hugr/src/builder/build_traits.rs | 4 +- hugr/src/builder/cfg.rs | 4 +- hugr/src/builder/conditional.rs | 4 +- hugr/src/builder/dataflow.rs | 11 +- hugr/src/builder/module.rs | 2 +- hugr/src/extension.rs | 9 +- hugr/src/extension/infer/test.rs | 6 +- hugr/src/extension/op_def.rs | 53 ++++---- hugr/src/hugr/serialize/test.rs | 2 +- hugr/src/hugr/views/sibling_subgraph.rs | 5 +- hugr/src/ops.rs | 6 +- hugr/src/ops/constant.rs | 4 +- hugr/src/ops/controlflow.rs | 16 +-- hugr/src/ops/custom.rs | 18 +-- hugr/src/ops/dataflow.rs | 40 +++---- hugr/src/ops/leaf.rs | 10 +- hugr/src/ops/module.rs | 8 +- hugr/src/types.rs | 8 +- hugr/src/types/poly_func.rs | 77 ++++++------ hugr/src/types/signature.rs | 153 +++++++++++++++--------- 21 files changed, 251 insertions(+), 193 deletions(-) diff --git a/hugr/src/builder.rs b/hugr/src/builder.rs index c186b57cd..4e68a3105 100644 --- a/hugr/src/builder.rs +++ b/hugr/src/builder.rs @@ -245,7 +245,7 @@ pub(crate) mod test { } pub(super) fn build_main( - signature: PolyFuncType, + signature: PolyFuncType, f: impl FnOnce(FunctionBuilder<&mut Hugr>) -> Result>, BuildError>, ) -> Result { let mut module_builder = ModuleBuilder::new(); @@ -275,7 +275,7 @@ pub(crate) mod test { /// for tests which want to avoid having open extension variables after /// inference. Using DFGBuilder will default to a root node with an open /// extension variable - pub(crate) fn closed_dfg_root_hugr(signature: FunctionType) -> Hugr { + pub(crate) fn closed_dfg_root_hugr(signature: Signature) -> Hugr { let mut hugr = Hugr::new(NodeType::new_pure(ops::DFG { signature: signature.clone(), })); diff --git a/hugr/src/builder/build_traits.rs b/hugr/src/builder/build_traits.rs index 9703d65c3..367fac746 100644 --- a/hugr/src/builder/build_traits.rs +++ b/hugr/src/builder/build_traits.rs @@ -85,7 +85,7 @@ pub trait Container { fn define_function( &mut self, name: impl Into, - signature: PolyFuncType, + signature: PolyFuncType, ) -> Result, BuildError> { let body = signature.body().clone(); let f_node = self.add_child_node(NodeType::new_pure(ops::FuncDefn { @@ -296,7 +296,7 @@ pub trait Dataflow: Container { // TODO: Should this be one function, or should there be a temporary "op" one like with the others? fn dfg_builder( &mut self, - signature: FunctionType, + signature: Signature, input_extensions: Option, input_wires: impl IntoIterator, ) -> Result, BuildError> { diff --git a/hugr/src/builder/cfg.rs b/hugr/src/builder/cfg.rs index 1ac852b45..1e1bbe276 100644 --- a/hugr/src/builder/cfg.rs +++ b/hugr/src/builder/cfg.rs @@ -153,7 +153,7 @@ impl + AsRef> SubContainer for CFGBuilder { impl CFGBuilder { /// New CFG rooted HUGR builder - pub fn new(signature: FunctionType) -> Result { + pub fn new(signature: Signature) -> Result { let cfg_op = ops::CFG { signature: signature.clone(), }; @@ -251,7 +251,7 @@ impl + AsRef> CFGBuilder { /// This function will return an error if there is an error adding the node. pub fn simple_block_builder( &mut self, - signature: FunctionType, + signature: Signature, n_cases: usize, ) -> Result, BuildError> { self.block_builder( diff --git a/hugr/src/builder/conditional.rs b/hugr/src/builder/conditional.rs index e39c88451..252ee3193 100644 --- a/hugr/src/builder/conditional.rs +++ b/hugr/src/builder/conditional.rs @@ -1,7 +1,7 @@ use crate::extension::ExtensionRegistry; use crate::hugr::views::HugrView; use crate::ops::dataflow::DataflowOpTrait; -use crate::types::{FunctionType, TypeRow}; +use crate::types::{FunctionType, Signature, TypeRow}; use crate::ops; use crate::ops::handle::CaseID; @@ -192,7 +192,7 @@ impl ConditionalBuilder { impl CaseBuilder { /// Initialize a Case rooted HUGR - pub fn new(signature: FunctionType) -> Result { + pub fn new(signature: Signature) -> Result { let op = ops::Case { signature: signature.clone(), }; diff --git a/hugr/src/builder/dataflow.rs b/hugr/src/builder/dataflow.rs index 67865e13a..cfd21ff97 100644 --- a/hugr/src/builder/dataflow.rs +++ b/hugr/src/builder/dataflow.rs @@ -7,7 +7,7 @@ use std::marker::PhantomData; use crate::hugr::{HugrView, NodeType, ValidationError}; use crate::ops; -use crate::types::{FunctionType, PolyFuncType}; +use crate::types::{FunctionType, PolyFuncType, Signature}; use crate::extension::{ExtensionRegistry, ExtensionSet}; use crate::Node; @@ -26,7 +26,7 @@ impl + AsRef> DFGBuilder { pub(super) fn create_with_io( mut base: T, parent: Node, - signature: FunctionType, + signature: Signature, input_extensions: Option, ) -> Result { let num_in_wires = signature.input().len(); @@ -75,7 +75,7 @@ impl DFGBuilder { /// # Errors /// /// Error in adding DFG child nodes. - pub fn new(signature: FunctionType) -> Result, BuildError> { + pub fn new(signature: Signature) -> Result, BuildError> { let dfg_op = ops::DFG { signature: signature.clone(), }; @@ -146,7 +146,10 @@ impl FunctionBuilder { /// # Errors /// /// Error in adding DFG child nodes. - pub fn new(name: impl Into, signature: PolyFuncType) -> Result { + pub fn new( + name: impl Into, + signature: PolyFuncType, + ) -> Result { let body = signature.body().clone(); let op = ops::FuncDefn { signature, diff --git a/hugr/src/builder/module.rs b/hugr/src/builder/module.rs index f6b4b7f20..0d2b3cf24 100644 --- a/hugr/src/builder/module.rs +++ b/hugr/src/builder/module.rs @@ -105,7 +105,7 @@ impl + AsRef> ModuleBuilder { pub fn declare( &mut self, name: impl Into, - signature: PolyFuncType, + signature: PolyFuncType, ) -> Result, BuildError> { // TODO add param names to metadata let declare_n = self.add_child_node(NodeType::new_pure(ops::FuncDecl { diff --git a/hugr/src/extension.rs b/hugr/src/extension.rs index c2e58b0a8..fde533209 100644 --- a/hugr/src/extension.rs +++ b/hugr/src/extension.rs @@ -16,6 +16,7 @@ use crate::ops::constant::{ValueName, ValueNameRef}; use crate::ops::custom::{ExtensionOp, OpaqueOp}; use crate::ops::{self, OpName, OpNameRef}; use crate::types::type_param::{TypeArg, TypeArgError, TypeParam}; +use crate::types::Signature; use crate::types::{check_typevar_decl, CustomType, Substitution, TypeBound, TypeName}; use crate::types::{FunctionType, TypeNameRef}; @@ -172,8 +173,8 @@ pub enum SignatureError { "Incorrect result of type application in Call - cached {cached} but expected {expected}" )] CallIncorrectlyAppliesType { - cached: FunctionType, - expected: FunctionType, + cached: Signature, + expected: Signature, }, /// The result of the type application stored in a [LoadFunction] /// is not what we get by applying the type-args to the polymorphic function @@ -183,8 +184,8 @@ pub enum SignatureError { "Incorrect result of type application in LoadFunction - cached {cached} but expected {expected}" )] LoadFunctionIncorrectlyAppliesType { - cached: FunctionType, - expected: FunctionType, + cached: Signature, + expected: Signature, }, } diff --git a/hugr/src/extension/infer/test.rs b/hugr/src/extension/infer/test.rs index 74e0eb124..41899f2b9 100644 --- a/hugr/src/extension/infer/test.rs +++ b/hugr/src/extension/infer/test.rs @@ -21,7 +21,7 @@ use crate::{ }; use crate::type_row; -use crate::types::{FunctionType, Type, TypeRow}; +use crate::types::{FunctionType, Signature, Type, TypeRow}; use cool_asserts::assert_matches; use itertools::Itertools; @@ -281,7 +281,7 @@ fn create_with_io( hugr: &mut Hugr, parent: Node, op: impl Into, - op_sig: FunctionType, + op_sig: Signature, ) -> Result<[Node; 3], Box> { let op: OpType = op.into(); @@ -438,7 +438,7 @@ fn extension_adding_sequence() -> Result<(), Box> { Ok(()) } -fn make_opaque(extension: impl Into, signature: FunctionType) -> CustomOp { +fn make_opaque(extension: impl Into, signature: Signature) -> CustomOp { ops::custom::OpaqueOp::new(extension.into(), "", "".into(), vec![], signature).into() } diff --git a/hugr/src/extension/op_def.rs b/hugr/src/extension/op_def.rs index d91aa6890..3752aea81 100644 --- a/hugr/src/extension/op_def.rs +++ b/hugr/src/extension/op_def.rs @@ -24,7 +24,7 @@ pub trait CustomSignatureFunc: Send + Sync { arg_values: &[TypeArg], def: &'o OpDef, extension_registry: &ExtensionRegistry, - ) -> Result; + ) -> Result, SignatureError>; /// The declared type parameters which require values in order for signature to /// be computed. fn static_params(&self) -> &[TypeParam]; @@ -34,7 +34,10 @@ pub trait CustomSignatureFunc: Send + Sync { pub trait SignatureFromArgs: Send + Sync { /// Compute signature of node given /// values for the type parameters. - fn compute_signature(&self, arg_values: &[TypeArg]) -> Result; + fn compute_signature( + &self, + arg_values: &[TypeArg], + ) -> Result, SignatureError>; /// The declared type parameters which require values in order for signature to /// be computed. fn static_params(&self) -> &[TypeParam]; @@ -47,7 +50,7 @@ impl CustomSignatureFunc for T { arg_values: &[TypeArg], _def: &'o OpDef, _extension_registry: &ExtensionRegistry, - ) -> Result { + ) -> Result, SignatureError> { SignatureFromArgs::compute_signature(self, arg_values) } @@ -120,14 +123,14 @@ pub trait CustomLowerFunc: Send + Sync { #[derive(serde::Deserialize, serde::Serialize)] pub struct CustomValidator { #[serde(flatten)] - poly_func: PolyFuncType, + poly_func: PolyFuncType, #[serde(skip)] pub(crate) validate: Box, } impl CustomValidator { /// Encode a signature using a `PolyFuncType` - pub fn from_polyfunc(poly_func: impl Into) -> Self { + pub fn from_polyfunc(poly_func: impl Into>) -> Self { Self { poly_func: poly_func.into(), validate: Default::default(), @@ -137,7 +140,7 @@ impl CustomValidator { /// Encode a signature using a `PolyFuncType`, with a custom function for /// validating type arguments before returning the signature. pub fn new_with_validator( - poly_func: impl Into, + poly_func: impl Into>, validate: impl ValidateTypeArgs + 'static, ) -> Self { Self { @@ -186,8 +189,8 @@ impl From for SignatureFunc { } } -impl From for SignatureFunc { - fn from(v: PolyFuncType) -> Self { +impl From> for SignatureFunc { + fn from(v: PolyFuncType) -> Self { Self::TypeScheme(CustomValidator::from_polyfunc(v)) } } @@ -228,8 +231,8 @@ impl SignatureFunc { def: &OpDef, args: &[TypeArg], exts: &ExtensionRegistry, - ) -> Result { - let temp: PolyFuncType; + ) -> Result { + let temp: PolyFuncType; let (pf, args) = match &self { SignatureFunc::TypeScheme(custom) => { custom.validate.validate(args, def, exts)?; @@ -249,7 +252,9 @@ impl SignatureFunc { // TODO bring this assert back once resource inference is done? // https://github.com/CQCL/hugr/issues/388 // debug_assert!(res.extension_reqs.contains(def.extension())); - Ok(res) + + // If there are any row variables left, this will fail with an error: + res.try_into() } } @@ -330,7 +335,7 @@ impl OpDef { exts: &ExtensionRegistry, var_decls: &[TypeParam], ) -> Result<(), SignatureError> { - let temp: PolyFuncType; // to keep alive + let temp: PolyFuncType; // to keep alive let (pf, args) = match &self.signature_func { SignatureFunc::TypeScheme(ts) => (&ts.poly_func, args), SignatureFunc::CustomFunc(custom) => { @@ -356,7 +361,7 @@ impl OpDef { &self, args: &[TypeArg], exts: &ExtensionRegistry, - ) -> Result { + ) -> Result { self.signature_func.compute_signature(self, args, exts) } @@ -408,7 +413,7 @@ impl OpDef { // The type scheme may contain row variables so be of variable length; // these will have to be substituted to fixed-length concrete types when // the OpDef is instantiated into an actual OpType. - ts.poly_func.validate_var_len(exts)?; + ts.poly_func.validate(exts)?; } Ok(()) } @@ -486,8 +491,8 @@ mod test { use crate::ops::{CustomOp, OpName}; use crate::std_extensions::collections::{EXTENSION, LIST_TYPENAME}; use crate::types::type_param::TypeArgError; - use crate::types::Type; use crate::types::{type_param::TypeParam, FunctionType, PolyFuncType, TypeArg, TypeBound}; + use crate::types::{FunctionType, Type}; use crate::{const_extension_ids, Extension}; const_extension_ids! { @@ -520,7 +525,7 @@ mod test { let list_usize = Type::new_extension(list_def.instantiate(vec![TypeArg::Type { ty: USIZE_T }])?); - let mut dfg = DFGBuilder::new(FunctionType::new_endo(vec![list_usize]))?; + let mut dfg = DFGBuilder::new(FunctionType::try_new_endo(vec![list_usize])?)?; let rev = dfg.add_dataflow_op( CustomOp::new_extension( e.instantiate_extension_op(&OP_NAME, vec![TypeArg::Type { ty: USIZE_T }], ®) @@ -544,7 +549,7 @@ mod test { fn compute_signature( &self, arg_values: &[TypeArg], - ) -> Result { + ) -> Result, SignatureError> { const TP: TypeParam = TypeParam::Type { b: TypeBound::Any }; let [TypeArg::BoundedNat { n }] = arg_values else { return Err(SignatureError::InvalidTypeArgs); @@ -572,10 +577,10 @@ mod test { let args = [TypeArg::BoundedNat { n: 3 }, USIZE_T.into()]; assert_eq!( def.compute_signature(&args, &PRELUDE_REGISTRY), - Ok(FunctionType::new( + Ok(FunctionType::try_new( vec![USIZE_T; 3], vec![Type::new_tuple(vec![USIZE_T; 3])] - )) + )?) ); assert_eq!(def.validate_args(&args, &PRELUDE_REGISTRY, &[]), Ok(())); @@ -585,10 +590,10 @@ mod test { let args = [TypeArg::BoundedNat { n: 3 }, tyvar.clone().into()]; assert_eq!( def.compute_signature(&args, &PRELUDE_REGISTRY), - Ok(FunctionType::new( + Ok(FunctionType::try_new( tyvars.clone(), vec![Type::new_tuple(tyvars)] - )) + )?) ); def.validate_args(&args, &PRELUDE_REGISTRY, &[TypeBound::Eq.into()]) .unwrap(); @@ -641,7 +646,7 @@ mod test { def.validate_args(&args, &EMPTY_REG, &decls).unwrap(); assert_eq!( def.compute_signature(&args, &EMPTY_REG), - Ok(FunctionType::new_endo(vec![tv])) + Ok(FunctionType::try_new_endo(tv)?) ); // But not with an external row variable let arg: TypeArg = Type::new_row_var_use(0, TypeBound::Eq).into(); @@ -665,7 +670,7 @@ mod test { let params: Vec = vec![TypeParam::Extensions]; let db_set = ExtensionSet::type_var(0); - let fun_ty = FunctionType::new_endo(vec![BOOL_T]).with_extension_delta(db_set); + let fun_ty = FunctionType::new_endo(BOOL_T).with_extension_delta(db_set); let def = e.add_op( "SimpleOp".into(), @@ -675,7 +680,7 @@ mod test { // Concrete extension set let es = ExtensionSet::singleton(&EXT_ID); - let exp_fun_ty = FunctionType::new_endo(vec![BOOL_T]).with_extension_delta(es.clone()); + let exp_fun_ty = FunctionType::try_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/src/hugr/serialize/test.rs b/hugr/src/hugr/serialize/test.rs index ab86c1e33..6c628966f 100644 --- a/hugr/src/hugr/serialize/test.rs +++ b/hugr/src/hugr/serialize/test.rs @@ -446,7 +446,7 @@ fn polyfunctype2() -> PolyFuncType { [TypeParam::new_list(TypeBound::Any)], FunctionType::new_endo(Type::new_tuple(Type::new_row_var_use(0, TypeBound::Any)))))] #[case(polyfunctype2())] -fn roundtrip_polyfunctype(#[case] poly_func_type: PolyFuncType) { +fn roundtrip_polyfunctype(#[case] poly_func_type: PolyFuncType) { check_testing_roundtrip(poly_func_type) } diff --git a/hugr/src/hugr/views/sibling_subgraph.rs b/hugr/src/hugr/views/sibling_subgraph.rs index ddc307509..1b6a7de97 100644 --- a/hugr/src/hugr/views/sibling_subgraph.rs +++ b/hugr/src/hugr/views/sibling_subgraph.rs @@ -18,11 +18,12 @@ use portgraph::{view::Subgraph, Direction, PortView}; use thiserror::Error; use crate::builder::{Container, FunctionBuilder}; +use crate::extension::SignatureError; use crate::hugr::{HugrMut, HugrView, RootTagged}; use crate::ops::dataflow::DataflowOpTrait; use crate::ops::handle::{ContainerHandle, DataflowOpID}; use crate::ops::{OpTag, OpTrait}; -use crate::types::{FunctionType, Type}; +use crate::types::{FunctionType, Signature, Type}; use crate::{Hugr, IncomingPort, Node, OutgoingPort, Port, SimpleReplacement}; /// A non-empty convex subgraph of a HUGR sibling graph. @@ -289,7 +290,7 @@ impl SiblingSubgraph { } /// The signature of the subgraph. - pub fn signature(&self, hugr: &impl HugrView) -> FunctionType { + pub fn signature(&self, hugr: &impl HugrView) -> Signature { let input = self .inputs .iter() diff --git a/hugr/src/ops.rs b/hugr/src/ops.rs index 2e48d1f9d..fcd37d572 100644 --- a/hugr/src/ops.rs +++ b/hugr/src/ops.rs @@ -10,7 +10,7 @@ pub mod module; pub mod tag; pub mod validate; use crate::extension::ExtensionSet; -use crate::types::{EdgeKind, FunctionType}; +use crate::types::{EdgeKind, FunctionType, Signature}; use crate::{Direction, OutgoingPort, Port}; use crate::{IncomingPort, PortIndex}; use paste::paste; @@ -342,7 +342,7 @@ pub trait OpTrait { /// The signature of the operation. /// /// Only dataflow operations have a signature, otherwise returns None. - fn dataflow_signature(&self) -> Option { + fn dataflow_signature(&self) -> Option { None } @@ -411,7 +411,7 @@ pub trait OpParent { } impl OpParent for T { - fn inner_function_type(&self) -> Option { + fn inner_function_type(&self) -> Option { Some(DataflowParent::inner_signature(self)) } } diff --git a/hugr/src/ops/constant.rs b/hugr/src/ops/constant.rs index 7e3a1ac37..1ea76f1b8 100644 --- a/hugr/src/ops/constant.rs +++ b/hugr/src/ops/constant.rs @@ -5,7 +5,7 @@ mod custom; use super::{NamedOp, OpName, OpTrait, StaticTag}; use super::{OpTag, OpType}; use crate::extension::ExtensionSet; -use crate::types::{CustomType, EdgeKind, FunctionType, SumType, SumTypeError, Type}; +use crate::types::{CustomType, EdgeKind, Signature, SumType, SumTypeError, Type}; use crate::{Hugr, HugrView}; use delegate::delegate; @@ -267,7 +267,7 @@ pub enum ConstTypeError { } /// Hugrs (even functions) inside Consts must be monomorphic -fn mono_fn_type(h: &Hugr) -> Result { +fn mono_fn_type(h: &Hugr) -> Result { if let Some(pf) = h.get_function_type() { if let Ok(ft) = pf.try_into() { return Ok(ft); diff --git a/hugr/src/ops/controlflow.rs b/hugr/src/ops/controlflow.rs index c09333ee3..20a4b4792 100644 --- a/hugr/src/ops/controlflow.rs +++ b/hugr/src/ops/controlflow.rs @@ -1,7 +1,7 @@ //! Control flow operations. use crate::extension::ExtensionSet; -use crate::types::{EdgeKind, FunctionType, Type, TypeRow}; +use crate::types::{EdgeKind, FunctionType, Signature, Type, TypeRow}; use crate::Direction; use super::dataflow::{DataflowOpTrait, DataflowParent}; @@ -29,7 +29,7 @@ impl DataflowOpTrait for TailLoop { "A tail-controlled loop" } - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { let [inputs, outputs] = [&self.just_inputs, &self.just_outputs].map(|row| row.extend(self.rest.iter())); FunctionType::new(inputs, outputs) @@ -73,7 +73,7 @@ impl DataflowOpTrait for Conditional { "HUGR conditional operation" } - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { let mut inputs = self.other_inputs.clone(); inputs .to_mut() @@ -95,7 +95,7 @@ impl Conditional { #[allow(missing_docs)] #[cfg_attr(test, derive(proptest_derive::Arbitrary))] pub struct CFG { - pub signature: FunctionType, + pub signature: Signature, } impl_op_name!(CFG); @@ -107,7 +107,7 @@ impl DataflowOpTrait for CFG { "A dataflow node defined by a child CFG" } - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { self.signature.clone() } } @@ -153,7 +153,7 @@ impl StaticTag for ExitBlock { } impl DataflowParent for DataflowBlock { - fn inner_signature(&self) -> FunctionType { + fn inner_signature(&self) -> Signature { // The node outputs a Sum before the data outputs of the block node let sum_type = Type::new_sum(self.sum_rows.clone()); let mut node_outputs = vec![sum_type]; @@ -250,7 +250,7 @@ impl BasicBlock for ExitBlock { /// Case ops - nodes valid inside Conditional nodes. pub struct Case { /// The signature of the contained dataflow graph. - pub signature: FunctionType, + pub signature: Signature, } impl_op_name!(Case); @@ -260,7 +260,7 @@ impl StaticTag for Case { } impl DataflowParent for Case { - fn inner_signature(&self) -> FunctionType { + fn inner_signature(&self) -> Signature { self.signature.clone() } } diff --git a/hugr/src/ops/custom.rs b/hugr/src/ops/custom.rs index 31248385f..0d9a86b43 100644 --- a/hugr/src/ops/custom.rs +++ b/hugr/src/ops/custom.rs @@ -11,8 +11,8 @@ use { use crate::extension::{ConstFoldResult, ExtensionId, ExtensionRegistry, OpDef, SignatureError}; use crate::hugr::hugrmut::sealed::HugrMutInternals; use crate::hugr::{HugrView, NodeType}; -use crate::types::EdgeKind; use crate::types::{type_param::TypeArg, FunctionType}; +use crate::types::{EdgeKind, Signature}; use crate::{ops, Hugr, IncomingPort, Node}; use super::dataflow::DataflowOpTrait; @@ -129,7 +129,7 @@ impl DataflowOpTrait for CustomOp { } /// The signature of the operation. - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { match self { Self::Opaque(op) => op.signature.clone(), Self::Extension(ext_op) => ext_op.signature(), @@ -175,7 +175,7 @@ impl From for CustomOp { pub struct ExtensionOp { def: Arc, args: Vec, - signature: FunctionType, // Cache + signature: Signature, // Cache } impl ExtensionOp { @@ -265,7 +265,7 @@ impl DataflowOpTrait for ExtensionOp { self.def().description() } - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { self.signature.clone() } } @@ -280,7 +280,7 @@ pub struct OpaqueOp { #[cfg_attr(test, proptest(strategy = "any_nonempty_string()"))] description: String, // cache in advance so description() can return &str args: Vec, - signature: FunctionType, + signature: Signature, } fn qualify_name(res_id: &ExtensionId, op_name: &OpNameRef) -> OpName { @@ -294,7 +294,7 @@ impl OpaqueOp { op_name: impl Into, description: String, args: impl Into>, - signature: FunctionType, + signature: Signature, ) -> Self { Self { extension, @@ -336,7 +336,7 @@ impl DataflowOpTrait for OpaqueOp { &self.description } - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { self.signature.clone() } } @@ -417,8 +417,8 @@ pub enum CustomOpError { SignatureMismatch { extension: ExtensionId, op: OpName, - stored: FunctionType, - computed: FunctionType, + stored: Signature, + computed: Signature, }, } diff --git a/hugr/src/ops/dataflow.rs b/hugr/src/ops/dataflow.rs index 54202ffc0..61df7ef38 100644 --- a/hugr/src/ops/dataflow.rs +++ b/hugr/src/ops/dataflow.rs @@ -4,7 +4,7 @@ use super::{impl_op_name, OpTag, OpTrait}; use crate::extension::{ExtensionRegistry, ExtensionSet, SignatureError}; use crate::ops::StaticTag; -use crate::types::{EdgeKind, FunctionType, PolyFuncType, Type, TypeArg, TypeRow}; +use crate::types::{EdgeKind, FunctionType, PolyFuncType, Signature, Type, TypeArg, TypeRow}; use crate::IncomingPort; #[cfg(test)] @@ -13,7 +13,7 @@ use ::proptest_derive::Arbitrary; pub(crate) trait DataflowOpTrait { const TAG: OpTag; fn description(&self) -> &str; - fn signature(&self) -> FunctionType; + fn signature(&self) -> Signature; /// The edge kind for the non-dataflow or constant inputs of the operation, /// not described by the signature. @@ -99,7 +99,7 @@ impl DataflowOpTrait for Input { None } - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { FunctionType::new(TypeRow::new(), self.types.clone()) } } @@ -112,7 +112,7 @@ impl DataflowOpTrait for Output { // Note: We know what the input extensions should be, so we *could* give an // instantiated Signature instead - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { FunctionType::new(self.types.clone(), TypeRow::new()) } @@ -128,7 +128,7 @@ impl OpTrait for T { fn tag(&self) -> OpTag { T::TAG } - fn dataflow_signature(&self) -> Option { + fn dataflow_signature(&self) -> Option { Some(DataflowOpTrait::signature(self)) } fn extension_delta(&self) -> ExtensionSet { @@ -159,9 +159,9 @@ impl StaticTag for T { #[cfg_attr(test, derive(Arbitrary))] pub struct Call { /// Signature of function being called - func_sig: PolyFuncType, + func_sig: PolyFuncType, type_args: Vec, - instantiation: FunctionType, // Cache, so we can fail in try_new() not in signature() + instantiation: Signature, // Cache, so we can fail in try_new() not in signature() } impl_op_name!(Call); @@ -172,7 +172,7 @@ impl DataflowOpTrait for Call { "Call a function directly" } - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { self.instantiation.clone() } @@ -186,7 +186,7 @@ impl Call { /// /// [TypeParam]: crate::types::type_param::TypeParam pub fn try_new( - func_sig: PolyFuncType, + func_sig: PolyFuncType, type_args: impl Into>, exts: &ExtensionRegistry, ) -> Result { @@ -253,7 +253,7 @@ impl Call { #[cfg_attr(test, derive(Arbitrary))] pub struct CallIndirect { /// Signature of function being called - pub signature: FunctionType, + pub signature: Signature, } impl_op_name!(CallIndirect); @@ -264,7 +264,7 @@ impl DataflowOpTrait for CallIndirect { "Call a function indirectly" } - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { let mut s = self.signature.clone(); s.input .to_mut() @@ -288,7 +288,7 @@ impl DataflowOpTrait for LoadConstant { "Load a static constant in to the local dataflow graph" } - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { FunctionType::new(TypeRow::new(), vec![self.datatype.clone()]) } @@ -329,9 +329,9 @@ impl LoadConstant { #[cfg_attr(test, derive(Arbitrary))] pub struct LoadFunction { /// Signature of the function - func_sig: PolyFuncType, + func_sig: PolyFuncType, type_args: Vec, - signature: FunctionType, // Cache, so we can fail in try_new() not in signature() + signature: Signature, // Cache, so we can fail in try_new() not in signature() } impl_op_name!(LoadFunction); impl DataflowOpTrait for LoadFunction { @@ -341,7 +341,7 @@ impl DataflowOpTrait for LoadFunction { "Load a static function in to the local dataflow graph" } - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { self.signature.clone() } @@ -355,7 +355,7 @@ impl LoadFunction { /// /// [TypeParam]: crate::types::type_param::TypeParam pub fn try_new( - func_sig: PolyFuncType, + func_sig: PolyFuncType, type_args: impl Into>, exts: &ExtensionRegistry, ) -> Result { @@ -408,7 +408,7 @@ impl LoadFunction { /// Operations that is the parent of a dataflow graph. pub trait DataflowParent { /// Signature of the inner dataflow graph. - fn inner_signature(&self) -> FunctionType; + fn inner_signature(&self) -> Signature; } /// A simply nested dataflow graph. @@ -416,13 +416,13 @@ pub trait DataflowParent { #[cfg_attr(test, derive(Arbitrary))] pub struct DFG { /// Signature of DFG node - pub signature: FunctionType, + pub signature: Signature, } impl_op_name!(DFG); impl DataflowParent for DFG { - fn inner_signature(&self) -> FunctionType { + fn inner_signature(&self) -> Signature { self.signature.clone() } } @@ -434,7 +434,7 @@ impl DataflowOpTrait for DFG { "A simply nested dataflow graph" } - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { self.inner_signature() } } diff --git a/hugr/src/ops/leaf.rs b/hugr/src/ops/leaf.rs index 4fc84e85e..8e43af053 100644 --- a/hugr/src/ops/leaf.rs +++ b/hugr/src/ops/leaf.rs @@ -119,7 +119,7 @@ impl DataflowOpTrait for Noop { } /// The signature of the operation. - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { FunctionType::new(vec![self.ty.clone()], vec![self.ty.clone()]) } @@ -141,7 +141,7 @@ impl DataflowOpTrait for MakeTuple { } /// The signature of the operation. - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { FunctionType::new(self.tys.clone(), vec![Type::new_tuple(self.tys.clone())]) } @@ -163,7 +163,7 @@ impl DataflowOpTrait for UnpackTuple { } /// The signature of the operation. - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { FunctionType::new(vec![Type::new_tuple(self.tys.clone())], self.tys.clone()) } @@ -185,7 +185,7 @@ impl DataflowOpTrait for Tag { } /// The signature of the operation. - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { FunctionType::new( self.variants .get(self.tag) @@ -213,7 +213,7 @@ impl DataflowOpTrait for Lift { } /// The signature of the operation. - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { FunctionType::new(self.type_row.clone(), self.type_row.clone()) .with_extension_delta(ExtensionSet::singleton(&self.new_extension)) } diff --git a/hugr/src/ops/module.rs b/hugr/src/ops/module.rs index 40c189b68..725ac0819 100644 --- a/hugr/src/ops/module.rs +++ b/hugr/src/ops/module.rs @@ -7,7 +7,7 @@ use { ::proptest_derive::Arbitrary, }; -use crate::types::{EdgeKind, FunctionType, PolyFuncType}; +use crate::types::{EdgeKind, FunctionType, PolyFuncType, Signature}; use crate::types::{Type, TypeBound}; use super::dataflow::DataflowParent; @@ -45,7 +45,7 @@ pub struct FuncDefn { #[cfg_attr(test, proptest(strategy = "any_nonempty_string()"))] pub name: String, /// Signature of the function - pub signature: PolyFuncType, + pub signature: PolyFuncType, } impl_op_name!(FuncDefn); @@ -54,7 +54,7 @@ impl StaticTag for FuncDefn { } impl DataflowParent for FuncDefn { - fn inner_signature(&self) -> FunctionType { + fn inner_signature(&self) -> Signature { self.signature.body().clone() } } @@ -81,7 +81,7 @@ pub struct FuncDecl { #[cfg_attr(test, proptest(strategy = "any_nonempty_string()"))] pub name: String, /// Signature of the function - pub signature: PolyFuncType, + pub signature: PolyFuncType, } impl_op_name!(FuncDecl); diff --git a/hugr/src/types.rs b/hugr/src/types.rs index cb8cd0706..3307f8e0d 100644 --- a/hugr/src/types.rs +++ b/hugr/src/types.rs @@ -14,7 +14,7 @@ use crate::utils::display_list_with_separator; pub use check::SumTypeError; pub use custom::CustomType; pub use poly_func::PolyFuncType; -pub use signature::FunctionType; +pub use signature::{FunctionType, Signature}; use smol_str::SmolStr; pub use type_param::TypeArg; pub use type_row::TypeRow; @@ -51,7 +51,7 @@ pub enum EdgeKind { /// /// [FuncDecl]: crate::ops::FuncDecl /// [FuncDefn]: crate::ops::FuncDefn - Function(PolyFuncType), + Function(PolyFuncType), /// Explicitly enforce an ordering between nodes in a DDG. StateOrder, } @@ -395,9 +395,7 @@ impl Type { TypeEnum::Sum(SumType::Unit { .. }) => Ok(()), // No leaves there TypeEnum::Alias(_) => Ok(()), TypeEnum::Extension(custy) => custy.validate(extension_registry, var_decls), - // Function values may be passed around without knowing their arity - // (i.e. with row vars) as long as they are not called: - TypeEnum::Function(ft) => ft.validate_var_len(extension_registry, var_decls), + TypeEnum::Function(ft) => ft.validate(extension_registry, var_decls), TypeEnum::Variable(idx, bound) => check_typevar_decl(var_decls, *idx, &(*bound).into()), TypeEnum::RowVariable(idx, bound) => { if allow_row_vars { diff --git a/hugr/src/types/poly_func.rs b/hugr/src/types/poly_func.rs index e152a3c60..86c1a057c 100644 --- a/hugr/src/types/poly_func.rs +++ b/hugr/src/types/poly_func.rs @@ -9,8 +9,9 @@ use { proptest_derive::Arbitrary, }; +use super::signature::FunctionType; use super::type_param::{check_type_args, TypeArg, TypeParam}; -use super::{FunctionType, Substitution}; +use super::Substitution; /// A polymorphic type scheme, i.e. of a [FuncDecl], [FuncDefn] or [OpDef]. /// (Nodes/operations in the Hugr are not polymorphic.) @@ -27,7 +28,7 @@ use super::{FunctionType, Substitution}; "params.iter().map(ToString::to_string).join(\" \")", "body" )] -pub struct PolyFuncType { +pub struct PolyFuncType { /// The declared type parameters, i.e., these must be instantiated with /// the same number of [TypeArg]s before the function can be called. This /// defines the indices used by variables inside the body. @@ -35,11 +36,11 @@ pub struct PolyFuncType { params: Vec, /// Template for the function. May contain variables up to length of [Self::params] #[cfg_attr(test, proptest(strategy = "any_with::(params)"))] - body: FunctionType, + body: FunctionType, } -impl From for PolyFuncType { - fn from(body: FunctionType) -> Self { +impl From> for PolyFuncType { + fn from(body: FunctionType) -> Self { Self { params: vec![], body, @@ -47,11 +48,11 @@ impl From for PolyFuncType { } } -impl TryFrom for FunctionType { - /// If the PolyFuncType is not a monomorphic FunctionType, fail with the binders +impl TryFrom> for FunctionType { + /// If the PolyFuncType is not monomorphic, fail with its binders type Error = Vec; - fn try_from(value: PolyFuncType) -> Result { + fn try_from(value: PolyFuncType) -> Result { if value.params.is_empty() { Ok(value.body) } else { @@ -60,36 +61,26 @@ impl TryFrom for FunctionType { } } -impl PolyFuncType { +impl PolyFuncType { /// The type parameters, aka binders, over which this type is polymorphic pub fn params(&self) -> &[TypeParam] { &self.params } /// The body of the type, a function type. - pub fn body(&self) -> &FunctionType { + pub fn body(&self) -> &FunctionType { &self.body } /// Create a new PolyFuncType given the kinds of the variables it declares - /// and the underlying [FunctionType]. - pub fn new(params: impl Into>, body: FunctionType) -> Self { + /// and the underlying function type. + pub fn new(params: impl Into>, body: impl Into>) -> Self { Self { params: params.into(), - body, + body: body.into(), } } - /// Validates this instance, checking that the types in the body are - /// wellformed with respect to the registry, and the type variables declared. - /// Allows both inputs and outputs to contain [RowVariable]s - /// - /// [RowVariable]: [crate::types::TypeEnum::RowVariable] - pub fn validate_var_len(&self, reg: &ExtensionRegistry) -> Result<(), SignatureError> { - // TODO https://github.com/CQCL/hugr/issues/624 validate TypeParams declared here, too - self.body.validate_var_len(reg, &self.params) - } - /// Instantiates an outer [PolyFuncType], i.e. with no free variables /// (as ensured by [Self::validate]), into a monomorphic type. /// @@ -100,7 +91,7 @@ impl PolyFuncType { &self, args: &[TypeArg], ext_reg: &ExtensionRegistry, - ) -> Result { + ) -> Result, SignatureError> { // Check that args are applicable, and that we have a value for each binder, // i.e. each possible free variable within the body. check_type_args(args, &self.params)?; @@ -108,6 +99,18 @@ impl PolyFuncType { } } +impl PolyFuncType { + /// Validates this instance, checking that the types in the body are + /// wellformed with respect to the registry, and the type variables declared. + /// Allows both inputs and outputs to contain [RowVariable]s + /// + /// [RowVariable]: [crate::types::TypeEnum::RowVariable] + pub fn validate(&self, reg: &ExtensionRegistry) -> Result<(), SignatureError> { + // TODO https://github.com/CQCL/hugr/issues/624 validate TypeParams declared here, too + self.body.validate(reg, &self.params) + } +} + #[cfg(test)] pub(crate) mod test { use std::num::NonZeroU64; @@ -132,14 +135,14 @@ pub(crate) mod test { ExtensionRegistry::try_new([PRELUDE.to_owned(), EXTENSION.to_owned()]).unwrap(); } - impl PolyFuncType { + impl PolyFuncType { fn new_validated( params: impl Into>, body: FunctionType, extension_registry: &ExtensionRegistry, ) -> Result { let res = Self::new(params, body); - res.validate_var_len(extension_registry)?; + res.validate(extension_registry)?; Ok(res) } } @@ -171,10 +174,6 @@ pub(crate) mod test { Ok(()) } - fn id_fn(t: Type) -> FunctionType { - FunctionType::new(vec![t.clone()], vec![t]) - } - #[test] fn test_mismatched_args() -> Result<(), SignatureError> { let ar_def = PRELUDE.get_type("array").unwrap(); @@ -184,8 +183,11 @@ pub(crate) mod test { // Valid schema... let good_array = Type::new_extension(ar_def.instantiate([tyvar.clone(), szvar.clone()])?); - let good_ts = - PolyFuncType::new_validated(typarams.clone(), id_fn(good_array), &PRELUDE_REGISTRY)?; + let good_ts = PolyFuncType::new_validated( + typarams.clone(), + FunctionType::new_endo(good_array), + &PRELUDE_REGISTRY, + )?; // Sanity check (good args) good_ts.instantiate( @@ -223,8 +225,11 @@ pub(crate) mod test { PRELUDE_ID, TypeBound::Any, )); - let bad_ts = - PolyFuncType::new_validated(typarams.clone(), id_fn(bad_array), &PRELUDE_REGISTRY); + let bad_ts = PolyFuncType::new_validated( + typarams.clone(), + FunctionType::new_endo(bad_array), + &PRELUDE_REGISTRY, + ); assert_eq!(bad_ts.err(), Some(arg_err)); Ok(()) @@ -235,7 +240,7 @@ pub(crate) mod test { // Variables in args have different bounds from variable declaration let tv = TypeArg::new_var_use(0, TypeBound::Copyable.into()); let list_def = EXTENSION.get_type(&LIST_TYPENAME).unwrap(); - let body_type = id_fn(Type::new_extension(list_def.instantiate([tv])?)); + let body_type = FunctionType::new_endo(Type::new_extension(list_def.instantiate([tv])?)); for decl in [ TypeParam::Extensions, TypeParam::List { @@ -291,7 +296,7 @@ pub(crate) mod test { let make_scheme = |tp: TypeParam| { PolyFuncType::new_validated( [tp.clone()], - id_fn(Type::new_extension(CustomType::new( + FunctionType::new_endo(Type::new_extension(CustomType::new( TYPE_NAME, [TypeArg::new_var_use(0, tp)], EXT_ID, diff --git a/hugr/src/types/signature.rs b/hugr/src/types/signature.rs index 1cf731eda..6425c154c 100644 --- a/hugr/src/types/signature.rs +++ b/hugr/src/types/signature.rs @@ -16,12 +16,14 @@ use {crate::proptest::RecursionDepth, ::proptest::prelude::*, proptest_derive::A #[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[cfg_attr(test, derive(Arbitrary), proptest(params = "RecursionDepth"))] -/// Describes the edges required to/from a node, and thus, also the type of a [Graph]. -/// This includes both the concept of "signature" in the spec, -/// and also the target (value) of a call (static). +/// Describes the edges required to/from a node (when ROWVARS=false); +/// or (when ROWVARS=true) the type of a [Graph] or the inputs/outputs from an OpDef +/// +/// ROWVARS specifies whether it may contain [RowVariable]s or not. /// /// [Graph]: crate::ops::constant::Value::Function -pub struct FunctionType { +/// [RowVariable]: crate::types::TypeEnum::RowVariable +pub struct FunctionType { /// Value inputs of the function. #[cfg_attr(test, proptest(strategy = "any_with::(params)"))] pub input: TypeRow, @@ -32,14 +34,28 @@ pub struct FunctionType { pub extension_reqs: ExtensionSet, } -impl FunctionType { +/// The concept of "signature" in the spec - the edges required to/from a node or graph +/// and also the target (value) of a call (static). +pub type Signature = FunctionType; // TODO: rename to "Signature" + +impl FunctionType { /// Builder method, add extension_reqs to an FunctionType pub fn with_extension_delta(mut self, rs: impl Into) -> Self { self.extension_reqs = self.extension_reqs.union(rs.into()); self } - pub(super) fn validate_var_len( + pub(crate) fn substitute(&self, tr: &Substitution) -> Self { + Self { + input: self.input.substitute(tr), + output: self.output.substitute(tr), + extension_reqs: self.extension_reqs.substitute(tr), + } + } +} + +impl FunctionType { + pub(super) fn validate( &self, extension_registry: &ExtensionRegistry, var_decls: &[TypeParam], @@ -49,38 +65,82 @@ impl FunctionType { .validate_var_len(extension_registry, var_decls)?; self.extension_reqs.validate(var_decls) } - - pub(crate) fn substitute(&self, tr: &Substitution) -> Self { - FunctionType { - input: self.input.substitute(tr), - output: self.output.substitute(tr), - extension_reqs: self.extension_reqs.substitute(tr), + pub fn new(input: impl Into, output: impl Into) -> Self { + Self { + input: input.into(), + output: output.into(), + extension_reqs: ExtensionSet::default(), } } + + pub fn new_endo(row: impl Into) -> Self { + let row = row.into(); + Self::new(row.clone(), row) + } + + /// If this FunctionType contains any row variables, return one. + pub fn find_rowvar(&self) -> Option<(usize, TypeBound)> { + self.input + .iter() + .chain(self.output.iter()) + .find_map(|t| match t.0 { + TypeEnum::RowVariable(idx, bound) => Some((idx, bound)), + _ => None, + }) + } } -impl FunctionType { - /// The number of wires in the signature. +impl FunctionType { + /// True if both inputs and outputs are necessarily empty. + /// (For [FunctionType], even after any possible substitution of row variables) #[inline(always)] pub fn is_empty(&self) -> bool { self.input.is_empty() && self.output.is_empty() } + + #[inline] + /// Returns the input row + pub fn input(&self) -> &TypeRow { + &self.input + } + + #[inline] + /// Returns the output row + pub fn output(&self) -> &TypeRow { + &self.output + } + + /// Converts to a tuple of the value inputs, extension delta, and value outputs + pub fn into_tuple(self) -> (TypeRow, ExtensionSet, TypeRow) { + (self.input, self.extension_reqs, self.output) + } } -impl FunctionType { +impl Signature { /// Create a new signature with specified inputs and outputs. - pub fn new(input: impl Into, output: impl Into) -> Self { - Self { - input: input.into(), - output: output.into(), - extension_reqs: ExtensionSet::new(), + pub fn try_new( + input: impl Into, + output: impl Into, + ) -> Result { + let input = input.into(); + let output = output.into(); + for t in input.iter().chain(output.iter()) { + if let TypeEnum::RowVariable(idx, _) = t.0 { + return Err(SignatureError::RowVarWhereTypeExpected { idx }); + } } + let extension_reqs = ExtensionSet::default(); + Ok(Self { + input, + output, + extension_reqs, + }) } /// Create a new signature with the same input and output types (signature of an endomorphic /// function). - pub fn new_endo(linear: impl Into) -> Self { + pub fn try_new_endo(linear: impl Into) -> Result { let linear = linear.into(); - Self::new(linear.clone(), linear) + Self::try_new(linear.clone(), linear) } /// Returns the type of a value [`Port`]. Returns `None` if the port is out @@ -98,7 +158,6 @@ impl FunctionType { /// of bounds. #[inline] pub fn in_port_type(&self, port: impl Into) -> Option<&Type> { - debug_assert!(self.find_rowvar().is_none()); self.input.get(port.into().index()) } @@ -106,7 +165,6 @@ impl FunctionType { /// of bounds. #[inline] pub fn out_port_type(&self, port: impl Into) -> Option<&Type> { - debug_assert!(self.find_rowvar().is_none()); self.output.get(port.into().index()) } @@ -114,7 +172,6 @@ impl FunctionType { /// of bounds. #[inline] pub fn in_port_type_mut(&mut self, port: impl Into) -> Option<&mut Type> { - debug_assert!(self.find_rowvar().is_none()); self.input.get_mut(port.into().index()) } @@ -122,7 +179,6 @@ impl FunctionType { /// of bounds. #[inline] pub fn out_port_type_mut(&mut self, port: impl Into) -> Option<&mut Type> { - debug_assert!(self.find_rowvar().is_none()); self.output.get_mut(port.into().index()) } @@ -179,31 +235,6 @@ impl FunctionType { self.types(Direction::Outgoing) } - #[inline] - /// Returns the input row - pub fn input(&self) -> &TypeRow { - &self.input - } - - #[inline] - /// Returns the output row - pub fn output(&self) -> &TypeRow { - &self.output - } -} - -impl FunctionType { - /// If this FunctionType contains any row variables, return one. - pub fn find_rowvar(&self) -> Option<(usize, TypeBound)> { - self.input - .iter() - .chain(self.output.iter()) - .find_map(|t| match t.0 { - TypeEnum::RowVariable(idx, bound) => Some((idx, bound)), - _ => None, - }) - } - /// Returns the `Port`s in the signature for a given direction. #[inline] pub fn ports(&self, dir: Direction) -> impl Iterator { @@ -225,7 +256,7 @@ impl FunctionType { } } -impl Display for FunctionType { +impl Display for FunctionType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if !self.input.is_empty() { self.input.fmt(f)?; @@ -238,14 +269,28 @@ impl Display for FunctionType { } } +impl TryFrom for Signature { + type Error = SignatureError; + + fn try_from(value: FunctionType) -> Result { + Ok(Self::try_new(value.input, value.output)?.with_extension_delta(value.extension_reqs)) + } +} + +impl From for FunctionType { + fn from(value: Signature) -> Self { + Self::new(value.input, value.output).with_extension_delta(value.extension_reqs) + } +} + #[cfg(test)] mod test { - use crate::{extension::prelude::USIZE_T, type_row}; + use crate::extension::prelude::USIZE_T; use super::*; #[test] fn test_function_type() { - let mut f_type = FunctionType::new(type_row![Type::UNIT], type_row![Type::UNIT]); + let mut f_type = FunctionType::try_new(Type::UNIT, Type::UNIT).unwrap(); assert_eq!(f_type.input_count(), 1); assert_eq!(f_type.output_count(), 1); From 066259e0faf2ddba5498c7c9715e8c083c03a381 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Fri, 17 May 2024 08:25:36 +0100 Subject: [PATCH 002/115] PartialEq FunctionType for Signature (?) --- hugr/src/types/signature.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/hugr/src/types/signature.rs b/hugr/src/types/signature.rs index 6425c154c..57a9bf905 100644 --- a/hugr/src/types/signature.rs +++ b/hugr/src/types/signature.rs @@ -283,6 +283,12 @@ impl From for FunctionType { } } +impl PartialEq for Signature { + fn eq(&self, other: &FunctionType) -> bool { + self.input == other.input && self.output == other.output && self.extension_reqs == other.extension_reqs + } +} + #[cfg(test)] mod test { use crate::extension::prelude::USIZE_T; From 077dabef894e33cde5c81a06befa7010ef8c96f9 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Fri, 24 May 2024 10:33:09 +0100 Subject: [PATCH 003/115] PolyFuncType defaults to --- hugr/src/extension/op_def.rs | 22 +++++++++++----------- hugr/src/types/poly_func.rs | 6 +++--- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/hugr/src/extension/op_def.rs b/hugr/src/extension/op_def.rs index 3752aea81..bf7d20065 100644 --- a/hugr/src/extension/op_def.rs +++ b/hugr/src/extension/op_def.rs @@ -24,7 +24,7 @@ pub trait CustomSignatureFunc: Send + Sync { arg_values: &[TypeArg], def: &'o OpDef, extension_registry: &ExtensionRegistry, - ) -> Result, SignatureError>; + ) -> Result; /// The declared type parameters which require values in order for signature to /// be computed. fn static_params(&self) -> &[TypeParam]; @@ -37,7 +37,7 @@ pub trait SignatureFromArgs: Send + Sync { fn compute_signature( &self, arg_values: &[TypeArg], - ) -> Result, SignatureError>; + ) -> Result; /// The declared type parameters which require values in order for signature to /// be computed. fn static_params(&self) -> &[TypeParam]; @@ -50,7 +50,7 @@ impl CustomSignatureFunc for T { arg_values: &[TypeArg], _def: &'o OpDef, _extension_registry: &ExtensionRegistry, - ) -> Result, SignatureError> { + ) -> Result { SignatureFromArgs::compute_signature(self, arg_values) } @@ -123,14 +123,14 @@ pub trait CustomLowerFunc: Send + Sync { #[derive(serde::Deserialize, serde::Serialize)] pub struct CustomValidator { #[serde(flatten)] - poly_func: PolyFuncType, + poly_func: PolyFuncType, #[serde(skip)] pub(crate) validate: Box, } impl CustomValidator { /// Encode a signature using a `PolyFuncType` - pub fn from_polyfunc(poly_func: impl Into>) -> Self { + pub fn from_polyfunc(poly_func: impl Into) -> Self { Self { poly_func: poly_func.into(), validate: Default::default(), @@ -140,7 +140,7 @@ impl CustomValidator { /// Encode a signature using a `PolyFuncType`, with a custom function for /// validating type arguments before returning the signature. pub fn new_with_validator( - poly_func: impl Into>, + poly_func: impl Into, validate: impl ValidateTypeArgs + 'static, ) -> Self { Self { @@ -189,8 +189,8 @@ impl From for SignatureFunc { } } -impl From> for SignatureFunc { - fn from(v: PolyFuncType) -> Self { +impl From for SignatureFunc { + fn from(v: PolyFuncType) -> Self { Self::TypeScheme(CustomValidator::from_polyfunc(v)) } } @@ -232,7 +232,7 @@ impl SignatureFunc { args: &[TypeArg], exts: &ExtensionRegistry, ) -> Result { - let temp: PolyFuncType; + let temp: PolyFuncType; let (pf, args) = match &self { SignatureFunc::TypeScheme(custom) => { custom.validate.validate(args, def, exts)?; @@ -335,7 +335,7 @@ impl OpDef { exts: &ExtensionRegistry, var_decls: &[TypeParam], ) -> Result<(), SignatureError> { - let temp: PolyFuncType; // to keep alive + let temp: PolyFuncType; // to keep alive let (pf, args) = match &self.signature_func { SignatureFunc::TypeScheme(ts) => (&ts.poly_func, args), SignatureFunc::CustomFunc(custom) => { @@ -549,7 +549,7 @@ mod test { fn compute_signature( &self, arg_values: &[TypeArg], - ) -> Result, SignatureError> { + ) -> Result { const TP: TypeParam = TypeParam::Type { b: TypeBound::Any }; let [TypeArg::BoundedNat { n }] = arg_values else { return Err(SignatureError::InvalidTypeArgs); diff --git a/hugr/src/types/poly_func.rs b/hugr/src/types/poly_func.rs index 86c1a057c..85b0f5a53 100644 --- a/hugr/src/types/poly_func.rs +++ b/hugr/src/types/poly_func.rs @@ -28,7 +28,7 @@ use super::Substitution; "params.iter().map(ToString::to_string).join(\" \")", "body" )] -pub struct PolyFuncType { +pub struct PolyFuncType { /// The declared type parameters, i.e., these must be instantiated with /// the same number of [TypeArg]s before the function can be called. This /// defines the indices used by variables inside the body. @@ -99,7 +99,7 @@ impl PolyFuncType { } } -impl PolyFuncType { +impl PolyFuncType { /// Validates this instance, checking that the types in the body are /// wellformed with respect to the registry, and the type variables declared. /// Allows both inputs and outputs to contain [RowVariable]s @@ -135,7 +135,7 @@ pub(crate) mod test { ExtensionRegistry::try_new([PRELUDE.to_owned(), EXTENSION.to_owned()]).unwrap(); } - impl PolyFuncType { + impl PolyFuncType { fn new_validated( params: impl Into>, body: FunctionType, From f2f420e6b7c1866588ea673bbff0bb72d5f10edc Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sat, 25 May 2024 08:48:44 +0100 Subject: [PATCH 004/115] Fix a few more funcs to return Signature --- hugr/src/builder/build_traits.rs | 2 +- hugr/src/builder/tail_loop.rs | 2 +- hugr/src/hugr.rs | 2 +- hugr/src/hugr/views.rs | 6 +++--- hugr/src/ops.rs | 2 +- hugr/src/ops/dataflow.rs | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/hugr/src/builder/build_traits.rs b/hugr/src/builder/build_traits.rs index 367fac746..88e26ddc4 100644 --- a/hugr/src/builder/build_traits.rs +++ b/hugr/src/builder/build_traits.rs @@ -334,7 +334,7 @@ pub trait Dataflow: Container { self, NodeType::new( ops::CFG { - signature: FunctionType::new(inputs.clone(), output_types.clone()) + signature: Signature::try_new(inputs.clone(), output_types.clone())? .with_extension_delta(extension_delta), }, input_extensions.into(), diff --git a/hugr/src/builder/tail_loop.rs b/hugr/src/builder/tail_loop.rs index 901324fe9..126560376 100644 --- a/hugr/src/builder/tail_loop.rs +++ b/hugr/src/builder/tail_loop.rs @@ -20,7 +20,7 @@ impl + AsRef> TailLoopBuilder { loop_node: Node, tail_loop: &ops::TailLoop, ) -> Result { - let signature = FunctionType::new(tail_loop.body_input_row(), tail_loop.body_output_row()); + let signature = Signature::new(tail_loop.body_input_row(), tail_loop.body_output_row())?; let dfg_build = DFGBuilder::create_with_io(base, loop_node, signature, None)?; Ok(TailLoopBuilder::from_dfg_builder(dfg_build)) diff --git a/hugr/src/hugr.rs b/hugr/src/hugr.rs index f53dfe482..2b6af84ac 100644 --- a/hugr/src/hugr.rs +++ b/hugr/src/hugr.rs @@ -108,7 +108,7 @@ impl NodeType { } /// Get the function type from the embedded op - pub fn op_signature(&self) -> Option { + pub fn op_signature(&self) -> Option { self.op.dataflow_signature() } diff --git a/hugr/src/hugr/views.rs b/hugr/src/hugr/views.rs index a22cd309c..eed100316 100644 --- a/hugr/src/hugr/views.rs +++ b/hugr/src/hugr/views.rs @@ -339,7 +339,7 @@ pub trait HugrView: sealed::HugrInternals { /// /// In contrast to [`get_function_type`][HugrView::get_function_type], this /// method always return a concrete [`FunctionType`]. - fn get_df_function_type(&self) -> Option { + fn get_df_function_type(&self) -> Option> { let op = self.get_optype(self.root()); op.inner_function_type() } @@ -354,7 +354,7 @@ pub trait HugrView: sealed::HugrInternals { /// of the function. /// /// Otherwise, returns `None`. - fn get_function_type(&self) -> Option { + fn get_function_type(&self) -> Option> { let op = self.get_optype(self.root()); match op { OpType::FuncDecl(decl) => Some(decl.signature.clone()), @@ -438,7 +438,7 @@ pub trait HugrView: sealed::HugrInternals { /// Get the "signature" (incoming and outgoing types) of a node, non-Value /// kind ports will be missing. - fn signature(&self, node: Node) -> Option { + fn signature(&self, node: Node) -> Option { self.get_optype(node).dataflow_signature() } diff --git a/hugr/src/ops.rs b/hugr/src/ops.rs index fcd37d572..2299eb1e1 100644 --- a/hugr/src/ops.rs +++ b/hugr/src/ops.rs @@ -405,7 +405,7 @@ pub trait OpParent { /// sibling graph. /// /// Non-container ops like `FuncDecl` return `None` even though they represent a function. - fn inner_function_type(&self) -> Option { + fn inner_function_type(&self) -> Option { None } } diff --git a/hugr/src/ops/dataflow.rs b/hugr/src/ops/dataflow.rs index 61df7ef38..d7d9699e0 100644 --- a/hugr/src/ops/dataflow.rs +++ b/hugr/src/ops/dataflow.rs @@ -371,7 +371,7 @@ impl LoadFunction { #[inline] /// Return the type of the function loaded by this op. - pub fn function_type(&self) -> &PolyFuncType { + pub fn function_type(&self) -> &PolyFuncType { &self.func_sig } From 71b6782c089f5fe7aea9f84b489ce701f027d398 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sat, 25 May 2024 15:37:14 +0100 Subject: [PATCH 005/115] Fix called_function_type to return PFT, update a validate --- hugr/src/hugr/validate.rs | 2 +- hugr/src/ops/dataflow.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/hugr/src/hugr/validate.rs b/hugr/src/hugr/validate.rs index 5a85ca8fe..0c6d536a9 100644 --- a/hugr/src/hugr/validate.rs +++ b/hugr/src/hugr/validate.rs @@ -321,7 +321,7 @@ impl<'a, 'b> ValidationContext<'a, 'b> { // Allow function "value" to have unknown arity. A Call node will have to provide // TypeArgs that produce a known arity, but a LoadFunction might pass the function // value ("function pointer") around without knowing how to call it. - EdgeKind::Function(pf) => pf.validate_var_len(self.extension_registry), + EdgeKind::Function(pf) => pf.validate(self.extension_registry), _ => Ok(()), } } diff --git a/hugr/src/ops/dataflow.rs b/hugr/src/ops/dataflow.rs index d7d9699e0..55f2f78e9 100644 --- a/hugr/src/ops/dataflow.rs +++ b/hugr/src/ops/dataflow.rs @@ -201,7 +201,7 @@ impl Call { #[inline] /// Return the signature of the function called by this op. - pub fn called_function_type(&self) -> &PolyFuncType { + pub fn called_function_type(&self) -> &PolyFuncType { &self.func_sig } From 6aeffbcb9bccf2f8ae1143aa27068fa8de6821d2 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sat, 25 May 2024 15:41:58 +0100 Subject: [PATCH 006/115] imports --- hugr/src/builder.rs | 2 +- hugr/src/builder/cfg.rs | 2 +- hugr/src/builder/tail_loop.rs | 2 +- hugr/src/extension/op_def.rs | 7 +++---- hugr/src/hugr.rs | 2 +- hugr/src/hugr/views.rs | 2 +- hugr/src/ops/constant.rs | 1 + hugr/src/ops/leaf.rs | 1 + 8 files changed, 10 insertions(+), 9 deletions(-) diff --git a/hugr/src/builder.rs b/hugr/src/builder.rs index 4e68a3105..d5633f92c 100644 --- a/hugr/src/builder.rs +++ b/hugr/src/builder.rs @@ -222,7 +222,7 @@ pub(crate) mod test { use crate::hugr::{views::HugrView, HugrMut, NodeType}; use crate::ops; - use crate::types::{FunctionType, PolyFuncType, Type}; + use crate::types::{FunctionType, PolyFuncType, Signature, Type}; use crate::{type_row, Hugr}; use super::handle::BuildHandle; diff --git a/hugr/src/builder/cfg.rs b/hugr/src/builder/cfg.rs index 1e1bbe276..6fa07c542 100644 --- a/hugr/src/builder/cfg.rs +++ b/hugr/src/builder/cfg.rs @@ -5,7 +5,7 @@ use super::{ BasicBlockID, BuildError, CfgID, Container, Dataflow, HugrBuilder, Wire, }; -use crate::ops::{self, handle::NodeHandle, DataflowBlock, DataflowParent, ExitBlock, OpType}; +use crate::{ops::{self, handle::NodeHandle, DataflowBlock, DataflowParent, ExitBlock, OpType}, types::Signature}; use crate::{ extension::{ExtensionRegistry, ExtensionSet}, types::FunctionType, diff --git a/hugr/src/builder/tail_loop.rs b/hugr/src/builder/tail_loop.rs index 126560376..5570b0623 100644 --- a/hugr/src/builder/tail_loop.rs +++ b/hugr/src/builder/tail_loop.rs @@ -1,7 +1,7 @@ use crate::ops; use crate::hugr::{views::HugrView, NodeType}; -use crate::types::{FunctionType, TypeRow}; +use crate::types::{FunctionType, Signature, TypeRow}; use crate::{Hugr, Node}; use super::build_traits::SubContainer; diff --git a/hugr/src/extension/op_def.rs b/hugr/src/extension/op_def.rs index bf7d20065..9665da09e 100644 --- a/hugr/src/extension/op_def.rs +++ b/hugr/src/extension/op_def.rs @@ -11,7 +11,7 @@ use super::{ use crate::ops::{OpName, OpNameRef}; use crate::types::type_param::{check_type_args, TypeArg, TypeParam}; -use crate::types::{FunctionType, PolyFuncType}; +use crate::types::{FunctionType, PolyFuncType, Signature}; use crate::Hugr; /// Trait necessary for binary computations of OpDef signature @@ -490,9 +490,8 @@ mod test { use crate::extension::{SignatureError, EMPTY_REG, PRELUDE_REGISTRY}; use crate::ops::{CustomOp, OpName}; use crate::std_extensions::collections::{EXTENSION, LIST_TYPENAME}; - use crate::types::type_param::TypeArgError; - use crate::types::{type_param::TypeParam, FunctionType, PolyFuncType, TypeArg, TypeBound}; - use crate::types::{FunctionType, Type}; + use crate::types::type_param::{TypeArgError, TypeParam}; + use crate::types::{FunctionType, PolyFuncType, TypeArg, TypeBound, Type}; use crate::{const_extension_ids, Extension}; const_extension_ids! { diff --git a/hugr/src/hugr.rs b/hugr/src/hugr.rs index 2b6af84ac..dcb0946ee 100644 --- a/hugr/src/hugr.rs +++ b/hugr/src/hugr.rs @@ -30,7 +30,7 @@ use crate::extension::infer_extensions; use crate::extension::{ExtensionRegistry, ExtensionSet, ExtensionSolution, InferExtensionError}; use crate::ops::custom::resolve_extension_ops; use crate::ops::{OpTag, OpTrait, OpType, DEFAULT_OPTYPE}; -use crate::types::FunctionType; +use crate::types::{FunctionType, Signature}; use crate::{Direction, Node}; use delegate::delegate; diff --git a/hugr/src/hugr/views.rs b/hugr/src/hugr/views.rs index eed100316..141c292bb 100644 --- a/hugr/src/hugr/views.rs +++ b/hugr/src/hugr/views.rs @@ -31,7 +31,7 @@ use crate::extension::ExtensionRegistry; use crate::ops::handle::NodeHandle; use crate::ops::{OpParent, OpTag, OpTrait, OpType}; -use crate::types::{EdgeKind, FunctionType}; +use crate::types::{EdgeKind, FunctionType, Signature}; use crate::types::{PolyFuncType, Type}; use crate::{Direction, IncomingPort, Node, OutgoingPort, Port}; diff --git a/hugr/src/ops/constant.rs b/hugr/src/ops/constant.rs index 1ea76f1b8..495879e93 100644 --- a/hugr/src/ops/constant.rs +++ b/hugr/src/ops/constant.rs @@ -434,6 +434,7 @@ mod test { use super::Value; use crate::builder::test::simple_dfg_hugr; use crate::std_extensions::arithmetic::int_types::ConstInt; + use crate::types::FunctionType; use crate::{ builder::{BuildError, DFGBuilder, Dataflow, DataflowHugr}, extension::{ diff --git a/hugr/src/ops/leaf.rs b/hugr/src/ops/leaf.rs index 8e43af053..5e0edfea8 100644 --- a/hugr/src/ops/leaf.rs +++ b/hugr/src/ops/leaf.rs @@ -5,6 +5,7 @@ use super::{impl_op_name, OpTag}; use crate::extension::ExtensionSet; +use crate::types::Signature; use crate::{ extension::ExtensionId, types::{EdgeKind, FunctionType, Type, TypeRow}, From 748b49fa9211febdaa4b57e6c462f04c6c2dc9f0 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sat, 25 May 2024 08:49:08 +0100 Subject: [PATCH 007/115] Builder/validation checks against rowvars now impossible --- hugr/src/builder/build_traits.rs | 9 --------- hugr/src/hugr/validate.rs | 13 ------------- 2 files changed, 22 deletions(-) diff --git a/hugr/src/builder/build_traits.rs b/hugr/src/builder/build_traits.rs index 88e26ddc4..e8e72075b 100644 --- a/hugr/src/builder/build_traits.rs +++ b/hugr/src/builder/build_traits.rs @@ -645,15 +645,6 @@ fn add_node_with_wires( inputs: impl IntoIterator, ) -> Result<(Node, usize), BuildError> { let nodetype: NodeType = nodetype.into(); - // Check there are no row variables, as that would prevent us - // from indexing into the node's ports in order to wire up - nodetype - .op_signature() - .as_ref() - .and_then(FunctionType::find_rowvar) - .map_or(Ok(()), |(idx, _)| { - Err(SignatureError::RowVarWhereTypeExpected { idx }) - })?; let num_outputs = nodetype.op().value_output_count(); let op_node = data_builder.add_child_node(nodetype.clone()); diff --git a/hugr/src/hugr/validate.rs b/hugr/src/hugr/validate.rs index 0c6d536a9..7f0754e8f 100644 --- a/hugr/src/hugr/validate.rs +++ b/hugr/src/hugr/validate.rs @@ -211,19 +211,6 @@ impl<'a, 'b> ValidationContext<'a, 'b> { } } - // Secondly, check that the node signature does not contain any row variables. - // (We do this here so it's before we try indexing into the ports of any nodes). - op_type - .dataflow_signature() - .as_ref() - .and_then(FunctionType::find_rowvar) - .map_or(Ok(()), |(idx, _)| { - Err(ValidationError::SignatureError { - node, - cause: SignatureError::RowVarWhereTypeExpected { idx }, - }) - })?; - // Thirdly that the node has correct children self.validate_children(node, node_type)?; From b180d96d14c4138d070f1808f998e1855c87e263 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sun, 26 May 2024 09:22:19 +0100 Subject: [PATCH 008/115] Try parametrizing Type(,Row, but not Enum) Do PartialEq better, and conversions Lots of special cases in TypeParam removed as we can rule them out statically (switch representation - a row variable is a TypeArg::Variable not a TypeArg::Type) --- hugr/src/types.rs | 165 +++++++++++++++++++++++++---------- hugr/src/types/serialize.rs | 37 ++++---- hugr/src/types/signature.rs | 98 ++++++++------------- hugr/src/types/type_param.rs | 52 ++++------- hugr/src/types/type_row.rs | 90 +++++++++++-------- 5 files changed, 240 insertions(+), 202 deletions(-) diff --git a/hugr/src/types.rs b/hugr/src/types.rs index 3307f8e0d..e9c3a1391 100644 --- a/hugr/src/types.rs +++ b/hugr/src/types.rs @@ -38,7 +38,7 @@ pub type TypeName = SmolStr; pub type TypeNameRef = str; /// The kinds of edges in a HUGR, excluding Hierarchy. -#[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)] +#[derive(Clone, PartialEq, Debug, serde::Serialize, serde::Deserialize)] #[non_exhaustive] pub enum EdgeKind { /// Control edges of a CFG region. @@ -130,7 +130,7 @@ pub enum SumType { Unit { size: u8 }, /// General case of a Sum type. #[allow(missing_docs)] - General { rows: Vec }, + General { rows: Vec> }, } impl std::fmt::Display for SumType { @@ -152,7 +152,7 @@ impl SumType { /// Initialize a new sum type. pub fn new(variants: impl IntoIterator) -> Self where - V: Into, + V: Into>, { let rows = variants.into_iter().map(Into::into).collect_vec(); @@ -170,7 +170,7 @@ impl SumType { } /// Report the tag'th variant, if it exists. - pub fn get_variant(&self, tag: usize) -> Option<&TypeRow> { + pub fn get_variant(&self, tag: usize) -> Option<&TypeRow> { match self { SumType::Unit { size } if tag < (*size as usize) => Some(Type::EMPTY_TYPEROW_REF), SumType::General { rows } => rows.get(tag), @@ -187,8 +187,8 @@ impl SumType { } } -impl From for Type { - fn from(sum: SumType) -> Type { +impl From for Type { + fn from(sum: SumType) -> Self { match sum { SumType::Unit { size } => Type::new_unit_sum(size), SumType::General { rows } => Type::new_sum(rows), @@ -223,13 +223,14 @@ pub enum TypeEnum { #[display(fmt = "Variable({})", _0)] Variable(usize, TypeBound), /// Variable index, and cache of inner TypeBound - matches a [TypeParam::List] of [TypeParam::Type] - /// of this bound (checked in validation) + /// of this bound (checked in validation). Should only exist for `Type`. #[display(fmt = "RowVar({})", _0)] RowVariable(usize, TypeBound), #[allow(missing_docs)] #[display(fmt = "{}", "_0")] Sum(#[cfg_attr(test, proptest(strategy = "any_with::(params)"))] SumType), } + impl TypeEnum { /// The smallest type bound that covers the whole type. fn least_upper_bound(&self) -> TypeBound { @@ -249,10 +250,10 @@ impl TypeEnum { } #[derive( - Clone, PartialEq, Debug, Eq, derive_more::Display, serde::Serialize, serde::Deserialize, + Clone, Debug, Eq, derive_more::Display, serde::Serialize, serde::Deserialize, )] #[display(fmt = "{}", "_0")] -#[serde(into = "serialize::SerSimpleType", from = "serialize::SerSimpleType")] +#[serde(into = "serialize::SerSimpleType", try_from = "serialize::SerSimpleType")] /// A HUGR type - the valid types of [EdgeKind::Value] and [EdgeKind::Const] edges. /// Such an edge is valid if the ports on either end agree on the [Type]. /// Types have an optional [TypeBound] which places limits on the valid @@ -273,24 +274,30 @@ impl TypeEnum { /// let func_type = Type::new_function(FunctionType::new_endo(vec![])); /// assert_eq!(func_type.least_upper_bound(), TypeBound::Copyable); /// ``` -pub struct Type(TypeEnum, TypeBound); +pub struct Type(TypeEnum, TypeBound); + +impl PartialEq> for Type { + fn eq(&self, other: &Type) -> bool { + self.0 == other.0 && self.1 == other.1 + } +} -impl Type { +impl Type { /// An empty `TypeRow`. Provided here for convenience - pub const EMPTY_TYPEROW: TypeRow = type_row![]; + pub const EMPTY_TYPEROW: TypeRow = type_row![]; /// Unit type (empty tuple). pub const UNIT: Self = Self(TypeEnum::Sum(SumType::Unit { size: 1 }), TypeBound::Eq); - const EMPTY_TYPEROW_REF: &'static TypeRow = &Self::EMPTY_TYPEROW; + const EMPTY_TYPEROW_REF: &'static TypeRow = &Self::EMPTY_TYPEROW; /// Initialize a new function type. - pub fn new_function(fun_ty: impl Into) -> Self { + pub fn new_function(fun_ty: impl Into>) -> Self { Self::new(TypeEnum::Function(Box::new(fun_ty.into()))) } /// Initialize a new tuple type by providing the elements. #[inline(always)] - pub fn new_tuple(types: impl Into) -> Self { + pub fn new_tuple(types: impl Into>) -> Self { let row = types.into(); match row.len() { 0 => Self::UNIT, @@ -300,7 +307,7 @@ impl Type { /// Initialize a new sum type by providing the possible variant types. #[inline(always)] - pub fn new_sum(variants: impl IntoIterator) -> Self where { + pub fn new_sum(variants: impl IntoIterator>) -> Self where { Self::new(TypeEnum::Sum(SumType::new(variants))) } @@ -317,6 +324,8 @@ impl Type { } fn new(type_e: TypeEnum) -> Self { + // private method - so we can be sure of this: + debug_assert!(RV || !matches!(type_e, TypeEnum::RowVariable(_, _))); let bound = type_e.least_upper_bound(); Self(type_e, bound) } @@ -335,19 +344,6 @@ impl Type { Self(TypeEnum::Variable(idx, bound), bound) } - /// New use (occurrence) of the row variable with specified index. - /// `bound` must be exactly that with which the variable was declared - /// (i.e. as a [TypeParam::List]` of a `[TypeParam::Type]` of that bound), - /// which may be narrower than required for the use. - /// For use in [OpDef] type schemes, or function types, only, - /// not [FuncDefn] type schemes or as a Hugr port type. - /// - /// [OpDef]: crate::extension::OpDef - /// [FuncDefn]: crate::ops::FuncDefn - pub const fn new_row_var_use(idx: usize, bound: TypeBound) -> Self { - Self(TypeEnum::RowVariable(idx, bound), bound) - } - /// Report the least upper [TypeBound] #[inline(always)] pub const fn least_upper_bound(&self) -> TypeBound { @@ -366,11 +362,6 @@ impl Type { TypeBound::Copyable.contains(self.least_upper_bound()) } - /// Tells if this Type is a row variable, i.e. could stand for any number >=0 of Types - pub fn is_row_var(&self) -> bool { - matches!(self.0, TypeEnum::RowVariable(_, _)) - } - /// Checks all variables used in the type are in the provided list /// of bound variables, rejecting any [RowVariable]s if `allow_row_vars` is False; /// and that for each [CustomType] the corresponding @@ -382,7 +373,6 @@ impl Type { /// [TypeDef]: crate::extension::TypeDef pub(crate) fn validate( &self, - allow_row_vars: bool, extension_registry: &ExtensionRegistry, var_decls: &[TypeParam], ) -> Result<(), SignatureError> { @@ -391,14 +381,16 @@ impl Type { match &self.0 { TypeEnum::Sum(SumType::General { rows }) => rows .iter() - .try_for_each(|row| row.validate_var_len(extension_registry, var_decls)), + .try_for_each(|row| row.validate(extension_registry, var_decls)), TypeEnum::Sum(SumType::Unit { .. }) => Ok(()), // No leaves there TypeEnum::Alias(_) => Ok(()), TypeEnum::Extension(custy) => custy.validate(extension_registry, var_decls), + // Function values may be passed around without knowing their arity + // (i.e. with row vars) as long as they are not called: TypeEnum::Function(ft) => ft.validate(extension_registry, var_decls), TypeEnum::Variable(idx, bound) => check_typevar_decl(var_decls, *idx, &(*bound).into()), TypeEnum::RowVariable(idx, bound) => { - if allow_row_vars { + if RV { check_typevar_decl(var_decls, *idx, &TypeParam::new_list(*bound)) } else { Err(SignatureError::RowVarWhereTypeExpected { idx: *idx }) @@ -413,15 +405,20 @@ impl Type { /// * If [Type::validate]`(false)` returns successfully, this method will return a Vec containing exactly one type /// * If [Type::validate]`(false)` fails, but `(true)` succeeds, this method may (depending on structure of self) /// return a Vec containing any number of [Type]s. These may (or not) pass [Type::validate] - fn substitute(&self, t: &Substitution) -> Vec { + fn subst_vec(&self, t: &Substitution) -> Vec { match &self.0 { - TypeEnum::RowVariable(idx, bound) => t.apply_rowvar(*idx, *bound), + TypeEnum::RowVariable(idx, bound) => { + assert!(RV); + let res = t.apply_rowvar(*idx, *bound); // these are Type's + // We need Types, so use try_into_(). Since we know RV==true, this cannot fail. + res.into_iter().map(|t| t.try_into_().unwrap()).collect() + } TypeEnum::Alias(_) | TypeEnum::Sum(SumType::Unit { .. }) => vec![self.clone()], TypeEnum::Variable(idx, bound) => { let TypeArg::Type { ty } = t.apply_var(*idx, &((*bound).into())) else { panic!("Variable was not a type - try validate() first") }; - vec![ty] + vec![ty.into_()] } TypeEnum::Extension(cty) => vec![Type::new_extension(cty.substitute(t))], TypeEnum::Function(bf) => vec![Type::new_function(bf.substitute(t))], @@ -432,6 +429,82 @@ impl Type { } } +impl Type { + fn substitute(&self, s: &Substitution) -> Self { + let v = self.subst_vec(s); + let [r] = v.try_into().unwrap(); // No row vars, so every Type produces exactly one + r + } +} + +impl Type { + /// Tells if this Type is a row variable, i.e. could stand for any number >=0 of Types + pub fn is_row_var(&self) -> bool { + matches!(self.0, TypeEnum::RowVariable(_, _)) + } + + /// New use (occurrence) of the row variable with specified index. + /// `bound` must match that with which the variable was declared + /// (i.e. as a [TypeParam::List]` of a `[TypeParam::Type]` of that bound). + /// For use in [OpDef], not [FuncDefn], type schemes only. + /// + /// [OpDef]: crate::extension::OpDef + /// [FuncDefn]: crate::ops::FuncDefn + pub const fn new_row_var_use(idx: usize, bound: TypeBound) -> Self { + Self(TypeEnum::RowVariable(idx, bound), bound) + } + + fn substitute(&self, s: &Substitution) -> Vec { + self.subst_vec(s) + } +} + +// ====== Conversions ====== +impl Type { + fn into_(self) -> Type { + Type(self.0, self.1) + } +} + +impl Type { + fn try_into_(self) -> Result, SignatureError> { + if !RV { + if let TypeEnum::RowVariable(idx, _) = self.0 { + return Err(SignatureError::RowVarWhereTypeExpected { idx }); + } + } + Ok(Type(self.0, self.1)) + } +} + +impl Type { + fn try_into_no_rv(self) -> Result, SignatureError> { + if let TypeEnum::RowVariable(idx, _) = self.0 { + assert!(RV); + return Err(SignatureError::RowVarWhereTypeExpected { idx }) + } + Ok(Type(self.0, self.1)) + } + + fn into_rv(self) -> Type { + Type(self.0, self.1) + } +} + +impl From> for Type { + fn from(value: Type) -> Self { + value.into_() // .into_rv also fine + } +} + +impl TryFrom> for Type { + type Error = SignatureError; + fn try_from(value: Type) -> Result { + value.try_into_() // .try_into_no_rv() also fine + } +} + + /// Details a replacement of type variables with a finite list of known values. /// (Variables out of the range of the list will result in a panic) pub(crate) struct Substitution<'a>(&'a [TypeArg], &'a ExtensionRegistry); @@ -446,7 +519,7 @@ impl<'a> Substitution<'a> { arg.clone() } - fn apply_rowvar(&self, idx: usize, bound: TypeBound) -> Vec { + fn apply_rowvar(&self, idx: usize, bound: TypeBound) -> Vec> { let arg = self .0 .get(idx) @@ -457,13 +530,13 @@ impl<'a> Substitution<'a> { TypeArg::Sequence { elems } => elems .iter() .map(|ta| match ta { - TypeArg::Type { ty } => ty.clone(), + TypeArg::Type { ty } => ty.clone().into(), _ => panic!("Not a list of types - call validate() ?"), }) .collect(), TypeArg::Type { ty } if matches!(ty.0, TypeEnum::RowVariable(_, _)) => { // Standalone "Type" can be used iff its actually a Row Variable not an actual (single) Type - vec![ty.clone()] + vec![ty.clone().into()] } _ => panic!("Not a type or list of types - call validate() ?"), } @@ -509,7 +582,7 @@ pub(crate) mod test { #[test] fn construct() { let t: Type = Type::new_tuple(vec![ - USIZE_T, + USIZE_T.into(), Type::new_function(FunctionType::new_endo(vec![])), Type::new_extension(CustomType::new( "my_custom", @@ -525,8 +598,8 @@ pub(crate) mod test { ); } - #[test] - fn sum_construct() { + #[rstest::rstest] + fn sum_construct() { let pred1 = Type::new_sum([Type::EMPTY_TYPEROW, Type::EMPTY_TYPEROW]); let pred2 = Type::new_unit_sum(2); diff --git a/hugr/src/types/serialize.rs b/hugr/src/types/serialize.rs index e4585d2f5..a82e653b9 100644 --- a/hugr/src/types/serialize.rs +++ b/hugr/src/types/serialize.rs @@ -3,6 +3,7 @@ use super::{FunctionType, SumType, Type, TypeArg, TypeBound, TypeEnum}; use super::custom::CustomType; use crate::extension::prelude::{array_type, QB_T, USIZE_T}; +use crate::extension::SignatureError; use crate::ops::AliasDecl; #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] @@ -10,7 +11,7 @@ use crate::ops::AliasDecl; pub(super) enum SerSimpleType { Q, I, - G(Box), + G(Box>), Sum(SumType), Array { inner: Box, len: u64 }, Opaque(CustomType), @@ -19,17 +20,11 @@ pub(super) enum SerSimpleType { R { i: usize, b: TypeBound }, } -impl From for SerSimpleType { - fn from(value: Type) -> Self { - if value == QB_T { - return SerSimpleType::Q; - } - if value == USIZE_T { - return SerSimpleType::I; - } - // TODO short circuiting for array. - let Type(value, _) = value; - match value { +impl From> for SerSimpleType { + fn from(value: Type) -> Self { + if value == QB_T { return SerSimpleType::Q }; + if value == USIZE_T { return SerSimpleType::I }; + match value.0 { TypeEnum::Extension(o) => SerSimpleType::Opaque(o), TypeEnum::Alias(a) => SerSimpleType::Alias(a), TypeEnum::Function(sig) => SerSimpleType::G(sig), @@ -40,20 +35,22 @@ impl From for SerSimpleType { } } -impl From for Type { - fn from(value: SerSimpleType) -> Type { - match value { - SerSimpleType::Q => QB_T, - SerSimpleType::I => USIZE_T, +impl TryFrom for Type { + type Error = SignatureError; + fn try_from(value: SerSimpleType) -> Result { + Ok(match value { + SerSimpleType::Q => QB_T.into_(), + SerSimpleType::I => USIZE_T.into_(), SerSimpleType::G(sig) => Type::new_function(*sig), SerSimpleType::Sum(st) => st.into(), SerSimpleType::Array { inner, len } => { - array_type(TypeArg::BoundedNat { n: len }, (*inner).into()) + array_type(TypeArg::BoundedNat { n: len }, (*inner).try_into().unwrap()).into_() } SerSimpleType::Opaque(o) => Type::new_extension(o), SerSimpleType::Alias(a) => Type::new_alias(a), SerSimpleType::V { i, b } => Type::new_var_use(i, b), - SerSimpleType::R { i, b } => Type::new_row_var_use(i, b), - } + // We can't use new_row_var because that returns Type not Type. + value@SerSimpleType::R { i, b } => Type::new(TypeEnum::RowVariable(i, b)).try_into_()? + }) } } diff --git a/hugr/src/types/signature.rs b/hugr/src/types/signature.rs index 57a9bf905..b0ceb774b 100644 --- a/hugr/src/types/signature.rs +++ b/hugr/src/types/signature.rs @@ -26,17 +26,17 @@ use {crate::proptest::RecursionDepth, ::proptest::prelude::*, proptest_derive::A pub struct FunctionType { /// Value inputs of the function. #[cfg_attr(test, proptest(strategy = "any_with::(params)"))] - pub input: TypeRow, + pub input: TypeRow, /// Value outputs of the function. #[cfg_attr(test, proptest(strategy = "any_with::(params)"))] - pub output: TypeRow, + pub output: TypeRow, /// The extension requirements which are added by the operation pub extension_reqs: ExtensionSet, } /// The concept of "signature" in the spec - the edges required to/from a node or graph /// and also the target (value) of a call (static). -pub type Signature = FunctionType; // TODO: rename to "Signature" +pub type Signature = FunctionType; impl FunctionType { /// Builder method, add extension_reqs to an FunctionType @@ -52,20 +52,8 @@ impl FunctionType { extension_reqs: self.extension_reqs.substitute(tr), } } -} -impl FunctionType { - pub(super) fn validate( - &self, - extension_registry: &ExtensionRegistry, - var_decls: &[TypeParam], - ) -> Result<(), SignatureError> { - self.input.validate_var_len(extension_registry, var_decls)?; - self.output - .validate_var_len(extension_registry, var_decls)?; - self.extension_reqs.validate(var_decls) - } - pub fn new(input: impl Into, output: impl Into) -> Self { + pub fn new(input: impl Into>, output: impl Into>) -> Self { Self { input: input.into(), output: output.into(), @@ -73,24 +61,11 @@ impl FunctionType { } } - pub fn new_endo(row: impl Into) -> Self { + pub fn new_endo(row: impl Into>) -> Self { let row = row.into(); Self::new(row.clone(), row) } - /// If this FunctionType contains any row variables, return one. - pub fn find_rowvar(&self) -> Option<(usize, TypeBound)> { - self.input - .iter() - .chain(self.output.iter()) - .find_map(|t| match t.0 { - TypeEnum::RowVariable(idx, bound) => Some((idx, bound)), - _ => None, - }) - } -} - -impl FunctionType { /// True if both inputs and outputs are necessarily empty. /// (For [FunctionType], even after any possible substitution of row variables) #[inline(always)] @@ -99,50 +74,43 @@ impl FunctionType { } #[inline] - /// Returns the input row - pub fn input(&self) -> &TypeRow { + /// Returns a row of the value inputs of the function. + pub fn input(&self) -> &TypeRow { &self.input } #[inline] - /// Returns the output row - pub fn output(&self) -> &TypeRow { + /// Returns a row of the value outputs of the function. + pub fn output(&self) -> &TypeRow { &self.output } +} - /// Converts to a tuple of the value inputs, extension delta, and value outputs - pub fn into_tuple(self) -> (TypeRow, ExtensionSet, TypeRow) { - (self.input, self.extension_reqs, self.output) +impl FunctionType { + pub(super) fn validate( + &self, + extension_registry: &ExtensionRegistry, + var_decls: &[TypeParam], + ) -> Result<(), SignatureError> { + self.input.validate(extension_registry, var_decls)?; + self.output + .validate(extension_registry, var_decls)?; + self.extension_reqs.validate(var_decls) + } + + /// If this FunctionType contains any row variables, return one. + pub fn find_rowvar(&self) -> Option<(usize, TypeBound)> { + self.input + .iter() + .chain(self.output.iter()) + .find_map(|t| match t.0 { + TypeEnum::RowVariable(idx, bound) => Some((idx, bound)), + _ => None, + }) } } impl Signature { - /// Create a new signature with specified inputs and outputs. - pub fn try_new( - input: impl Into, - output: impl Into, - ) -> Result { - let input = input.into(); - let output = output.into(); - for t in input.iter().chain(output.iter()) { - if let TypeEnum::RowVariable(idx, _) = t.0 { - return Err(SignatureError::RowVarWhereTypeExpected { idx }); - } - } - let extension_reqs = ExtensionSet::default(); - Ok(Self { - input, - output, - extension_reqs, - }) - } - /// Create a new signature with the same input and output types (signature of an endomorphic - /// function). - pub fn try_new_endo(linear: impl Into) -> Result { - let linear = linear.into(); - Self::try_new(linear.clone(), linear) - } - /// Returns the type of a value [`Port`]. Returns `None` if the port is out /// of bounds. #[inline] @@ -273,7 +241,9 @@ impl TryFrom for Signature { type Error = SignatureError; fn try_from(value: FunctionType) -> Result { - Ok(Self::try_new(value.input, value.output)?.with_extension_delta(value.extension_reqs)) + let input: TypeRow = value.input.try_into()?; + let output: TypeRow = value.output.try_into()?; + Ok(Self::new(input, output).with_extension_delta(value.extension_reqs)) } } diff --git a/hugr/src/types/type_param.rs b/hugr/src/types/type_param.rs index e7019fe7c..c16a34ded 100644 --- a/hugr/src/types/type_param.rs +++ b/hugr/src/types/type_param.rs @@ -213,7 +213,9 @@ impl From for TypeArg { } } -/// Variable in a TypeArg, that is not a [TypeArg::Type] or [TypeArg::Extensions], +/// Variable in a TypeArg, that is neither a [TypeArg::Extensions] +/// nor a single [TypeArg::Type] (i.e. not a [Type::new_var_use] +/// - it might be a [Type::new_row_var_use]). #[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)] pub struct TypeArgVariable { idx: usize, @@ -226,17 +228,11 @@ impl TypeArg { /// `decl` must be exactly that with which the variable was declared. pub fn new_var_use(idx: usize, decl: TypeParam) -> Self { match decl { + // Note a TypeParam::List of TypeParam::Type *cannot* be represented + // as a TypeArg::Type because the latter stores a Type i.e. only a single type, + // not a RowVariable. TypeParam::Type { b } => Type::new_var_use(idx, b).into(), - TypeParam::List { param: bx } if matches!(*bx, TypeParam::Type { .. }) => { - // There are two reasonable schemes for representing row variables: - // 1. TypeArg::Variable(idx, TypeParam::List(TypeParam::Type(typebound))) - // 2. TypeArg::Type(Type::new_row_var_use(idx, typebound)) - // Here we prefer the latter for canonicalization: TypeArgVariable's fields are non-pub - // so this pevents constructing malformed cases like the former. - let TypeParam::Type { b } = *bx else { panic!() }; - Type::new_row_var_use(idx, b).into() - } - // Similarly, prevent TypeArg::Variable(idx, TypeParam::Extensions) + // Prevent TypeArg::Variable(idx, TypeParam::Extensions) TypeParam::Extensions => TypeArg::Extensions { es: ExtensionSet::type_var(idx), }, @@ -257,8 +253,7 @@ impl TypeArg { var_decls: &[TypeParam], ) -> Result<(), SignatureError> { match self { - // Row variables are represented as 'TypeArg::Type's (see TypeArg::new_var_use) - TypeArg::Type { ty } => ty.validate(true, extension_registry, var_decls), + TypeArg::Type { ty } => ty.validate(extension_registry, var_decls), TypeArg::BoundedNat { .. } => Ok(()), TypeArg::Opaque { arg: custarg } => { // We could also add a facility to Extension to validate that the constant *value* @@ -274,13 +269,7 @@ impl TypeArg { TypeArg::Variable { v: TypeArgVariable { idx, cached_decl }, } => { - assert!( - match cached_decl { - TypeParam::Type { .. } => false, - TypeParam::List { param } if matches!(**param, TypeParam::Type { .. }) => - false, - _ => true, - }, + assert!(!matches!(cached_decl, TypeParam::Type {..}), "Malformed TypeArg::Variable {} - should be inconstructible", cached_decl ); @@ -293,14 +282,8 @@ impl TypeArg { pub(crate) fn substitute(&self, t: &Substitution) -> Self { match self { TypeArg::Type { ty } => { - let tys = ty.substitute(t).into_iter().map_into().collect::>(); - match as TryInto<[TypeArg; 1]>>::try_into(tys) { - Ok([ty]) => ty, - // Multiple elements can only have come from a row variable. - // So, we must be either in a TypeArg::Sequence; or a single Row Variable - // - fitting into a hole declared as a TypeParam::List (as per check_type_arg). - Err(elems) => TypeArg::Sequence { elems }, - } + // RowVariables are represented as TypeArg::Variable + ty.substitute(t).into() } TypeArg::BoundedNat { .. } => self.clone(), // We do not allow variables as bounds on BoundedNat's TypeArg::Opaque { @@ -383,28 +366,23 @@ pub fn check_type_arg(arg: &TypeArg, param: &TypeParam) -> Result<(), TypeArgErr _, ) if param.contains(cached_decl) => Ok(()), (TypeArg::Type { ty }, TypeParam::Type { b: bound }) - if bound.contains(ty.least_upper_bound()) && !ty.is_row_var() => + if bound.contains(ty.least_upper_bound()) => { Ok(()) } (TypeArg::Sequence { elems }, TypeParam::List { param }) => { elems.iter().try_for_each(|arg| { - // Also allow elements that are RowVars if fitting into a List of Types - if let (TypeArg::Type { ty }, TypeParam::Type { b }) = (arg, &**param) { - if ty.is_row_var() && b.contains(ty.least_upper_bound()) { - return Ok(()); - } - } check_type_arg(arg, param) }) } // Also allow a single "Type" to be used for a List *only* if the Type is a row variable // (i.e., it's not really a Type, it's multiple Types) - (TypeArg::Type { ty }, TypeParam::List { param }) + /* ALAN this is impossible, but what's it look like now? + (TypeArg::Type { ty }, TypeParam::List { param }) if ty.is_row_var() && param.contains(&ty.least_upper_bound().into()) => { Ok(()) - } + }*/ (TypeArg::Sequence { elems: items }, TypeParam::Tuple { params: types }) => { if items.len() != types.len() { diff --git a/hugr/src/types/type_row.rs b/hugr/src/types/type_row.rs index 5be3ddc2f..501caca72 100644 --- a/hugr/src/types/type_row.rs +++ b/hugr/src/types/type_row.rs @@ -19,12 +19,12 @@ use itertools::Itertools; #[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)] #[non_exhaustive] #[serde(transparent)] -pub struct TypeRow { +pub struct TypeRow { /// The datatypes in the row. - types: Cow<'static, [Type]>, + types: Cow<'static, [Type]>, } -impl Display for TypeRow { +impl Display for TypeRow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_char('[')?; display_list(self.types.as_ref(), f)?; @@ -32,7 +32,7 @@ impl Display for TypeRow { } } -impl TypeRow { +impl TypeRow { /// Create a new empty row. pub const fn new() -> Self { Self { @@ -41,31 +41,48 @@ impl TypeRow { } /// Returns a new `TypeRow` with `xs` concatenated onto `self`. - pub fn extend<'a>(&'a self, rest: impl IntoIterator) -> Self { + pub fn extend<'a>(&'a self, rest: impl IntoIterator>) -> Self { self.iter().chain(rest).cloned().collect_vec().into() } /// Returns a reference to the types in the row. - pub fn as_slice(&self) -> &[Type] { + pub fn as_slice(&self) -> &[Type] { &self.types } + /// Applies a substitution to the row. + /// For `TypeRow`, note this may change the length of the row. + /// For `TypeRow`, guaranteed not to change the length of the row. + pub(super) fn substitute(&self, s: &Substitution) -> Self { + self + .iter() + .flat_map(|ty| ty.subst_vec(s)) + .collect::>() + .into() + } + delegate! { to self.types { /// Iterator over the types in the row. - pub fn iter(&self) -> impl Iterator; - - /// Returns the number of types in the row. - pub fn len(&self) -> usize; + pub fn iter(&self) -> impl Iterator>; /// Mutable vector of the types in the row. - pub fn to_mut(&mut self) -> &mut Vec; + pub fn to_mut(&mut self) -> &mut Vec>; /// Allow access (consumption) of the contained elements - pub fn into_owned(self) -> Vec; + pub fn into_owned(self) -> Vec>; /// Returns `true` if the row contains no types. pub fn is_empty(&self) -> bool ; + } + } +} + +impl TypeRow { + delegate! { + to self.types { + /// Returns the number of types in the row. + pub fn len(&self) -> usize; #[inline(always)] /// Returns the type at the specified index. Returns `None` if out of bounds. @@ -78,39 +95,42 @@ impl TypeRow { pub fn get_mut(&mut self, offset: usize) -> Option<&mut Type>; } } +} - /// Applies a substitution to the row. Note this may change the length - /// if-and-only-if the row contains any [RowVariable]s. - /// - /// [RowVariable]: [crate::types::TypeEnum::RowVariable] - pub(super) fn substitute(&self, tr: &Substitution) -> TypeRow { - let res = self - .iter() - .flat_map(|ty| ty.substitute(tr)) - .collect::>() - .into(); - res - } - - pub(super) fn validate_var_len( +impl TypeRow { + pub(super) fn validate( &self, exts: &ExtensionRegistry, var_decls: &[TypeParam], ) -> Result<(), SignatureError> { self.iter() - .try_for_each(|t| t.validate(true, exts, var_decls)) + .try_for_each(|t| t.validate(exts, var_decls)) + } +} + +impl From for TypeRow { + fn from(value: TypeRow) -> Self { + Self::from(value.into_owned().into_iter().map_into().collect::>>()) + } +} + +impl TryFrom> for TypeRow { + type Error = SignatureError; + + fn try_from(value: TypeRow) -> Result { + Ok(Self::from(value.into_owned().into_iter().map(|t| t.try_into()).collect::,_>>()?)) } } -impl Default for TypeRow { +impl Default for TypeRow { fn default() -> Self { Self::new() } } -impl From for TypeRow +impl From for TypeRow where - F: Into>, + F: Into]>>, { fn from(types: F) -> Self { Self { @@ -119,23 +139,23 @@ where } } -impl From for TypeRow { - fn from(t: Type) -> Self { +impl From> for TypeRow { + fn from(t: Type) -> Self { Self { types: vec![t].into(), } } } -impl Deref for TypeRow { - type Target = [Type]; +impl Deref for TypeRow { + type Target = [Type]; fn deref(&self) -> &Self::Target { self.as_slice() } } -impl DerefMut for TypeRow { +impl DerefMut for TypeRow { fn deref_mut(&mut self) -> &mut Self::Target { self.types.to_mut() } From 7e0c49e674b2f6796f858126376ca6b9b3aae040 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sat, 25 May 2024 23:36:48 +0100 Subject: [PATCH 009/115] Fix a few new_sums --- hugr/src/builder/tail_loop.rs | 2 +- hugr/src/ops/controlflow.rs | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/hugr/src/builder/tail_loop.rs b/hugr/src/builder/tail_loop.rs index 5570b0623..760aaa5e1 100644 --- a/hugr/src/builder/tail_loop.rs +++ b/hugr/src/builder/tail_loop.rs @@ -20,7 +20,7 @@ impl + AsRef> TailLoopBuilder { loop_node: Node, tail_loop: &ops::TailLoop, ) -> Result { - let signature = Signature::new(tail_loop.body_input_row(), tail_loop.body_output_row())?; + let signature = Signature::new(tail_loop.body_input_row(), tail_loop.body_output_row()); let dfg_build = DFGBuilder::create_with_io(base, loop_node, signature, None)?; Ok(TailLoopBuilder::from_dfg_builder(dfg_build)) diff --git a/hugr/src/ops/controlflow.rs b/hugr/src/ops/controlflow.rs index 20a4b4792..0c16dc351 100644 --- a/hugr/src/ops/controlflow.rs +++ b/hugr/src/ops/controlflow.rs @@ -39,7 +39,7 @@ impl DataflowOpTrait for TailLoop { impl TailLoop { /// Build the output TypeRow of the child graph of a TailLoop node. pub(crate) fn body_output_row(&self) -> TypeRow { - let sum_type = Type::new_sum([self.just_inputs.clone(), self.just_outputs.clone()]); + let sum_type = Type::new_sum([self.just_inputs.clone().into(), self.just_outputs.clone().into()]); let mut outputs = vec![sum_type]; outputs.extend_from_slice(&self.rest); outputs.into() @@ -77,7 +77,7 @@ impl DataflowOpTrait for Conditional { let mut inputs = self.other_inputs.clone(); inputs .to_mut() - .insert(0, Type::new_sum(self.sum_rows.clone())); + .insert(0, Type::new_sum(self.sum_rows.iter().map(|r| r.clone().into()))); FunctionType::new(inputs, self.outputs.clone()) .with_extension_delta(self.extension_delta.clone()) } @@ -155,7 +155,7 @@ impl StaticTag for ExitBlock { impl DataflowParent for DataflowBlock { fn inner_signature(&self) -> Signature { // The node outputs a Sum before the data outputs of the block node - let sum_type = Type::new_sum(self.sum_rows.clone()); + let sum_type = Type::new_sum(self.sum_rows.iter().map(|r| r.clone().into())); let mut node_outputs = vec![sum_type]; node_outputs.extend_from_slice(&self.other_outputs); FunctionType::new(self.inputs.clone(), TypeRow::from(node_outputs)) From f4b8ad2f3a63ba296d2750039a6380972dfffbd1 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sat, 25 May 2024 23:41:28 +0100 Subject: [PATCH 010/115] imports --- hugr/src/builder/build_traits.rs | 4 ++-- hugr/src/builder/tail_loop.rs | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/hugr/src/builder/build_traits.rs b/hugr/src/builder/build_traits.rs index e8e72075b..1fec28d5b 100644 --- a/hugr/src/builder/build_traits.rs +++ b/hugr/src/builder/build_traits.rs @@ -19,8 +19,8 @@ use crate::{ types::EdgeKind, }; -use crate::extension::{ExtensionRegistry, ExtensionSet, SignatureError, PRELUDE_REGISTRY}; -use crate::types::{FunctionType, PolyFuncType, Type, TypeArg, TypeRow}; +use crate::extension::{ExtensionRegistry, ExtensionSet, PRELUDE_REGISTRY}; +use crate::types::{PolyFuncType, Signature, Type, TypeArg, TypeRow}; use itertools::Itertools; diff --git a/hugr/src/builder/tail_loop.rs b/hugr/src/builder/tail_loop.rs index 760aaa5e1..4c4a60218 100644 --- a/hugr/src/builder/tail_loop.rs +++ b/hugr/src/builder/tail_loop.rs @@ -1,7 +1,7 @@ use crate::ops; use crate::hugr::{views::HugrView, NodeType}; -use crate::types::{FunctionType, Signature, TypeRow}; +use crate::types::{Signature, TypeRow}; use crate::{Hugr, Node}; use super::build_traits::SubContainer; @@ -101,6 +101,7 @@ mod test { hugr::ValidationError, ops::Value, type_row, + types::FunctionType, }; use super::*; From 02aca28aa0cc3805781e4c28c3aad983df364630 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sun, 26 May 2024 19:20:00 +0100 Subject: [PATCH 011/115] Drop any_non_row_var, use any::> --- hugr/src/ops/constant.rs | 2 +- hugr/src/types.rs | 8 -------- 2 files changed, 1 insertion(+), 9 deletions(-) diff --git a/hugr/src/ops/constant.rs b/hugr/src/ops/constant.rs index 495879e93..799a08213 100644 --- a/hugr/src/ops/constant.rs +++ b/hugr/src/ops/constant.rs @@ -670,7 +670,7 @@ mod test { 32, // Target around 32 total elements 3, // Each collection is up to 3 elements long |element| { - (Type::any_non_row_var(), vec(element.clone(), 0..3)).prop_map( + (any::>(), vec(element.clone(), 0..3)).prop_map( |(typ, contents)| { OpaqueValue::new(ListValue::new( typ, diff --git a/hugr/src/types.rs b/hugr/src/types.rs index e9c3a1391..866f654fc 100644 --- a/hugr/src/types.rs +++ b/hugr/src/types.rs @@ -641,13 +641,5 @@ pub(crate) mod test { .boxed() } } - - impl super::Type { - pub fn any_non_row_var() -> BoxedStrategy { - any::() - .prop_filter("Cannot be a Row Variable", |t| !t.is_row_var()) - .boxed() - } - } } } From 824ca291f5924f57e6b70d2f086a8ffd8bca3946 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sun, 26 May 2024 19:32:14 +0100 Subject: [PATCH 012/115] Oops, missed a Signature::try_new, no need now --- hugr/src/builder/build_traits.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hugr/src/builder/build_traits.rs b/hugr/src/builder/build_traits.rs index 1fec28d5b..87e7aa70d 100644 --- a/hugr/src/builder/build_traits.rs +++ b/hugr/src/builder/build_traits.rs @@ -334,7 +334,7 @@ pub trait Dataflow: Container { self, NodeType::new( ops::CFG { - signature: Signature::try_new(inputs.clone(), output_types.clone())? + signature: Signature::new(inputs.clone(), output_types.clone()) .with_extension_delta(extension_delta), }, input_extensions.into(), From 12936c673720494fea6dba2215a0f50c5a0c80f7 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sun, 26 May 2024 19:34:07 +0100 Subject: [PATCH 013/115] Restore Eq for EdgeKind --- hugr/src/types.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hugr/src/types.rs b/hugr/src/types.rs index 866f654fc..fe8ffd2ca 100644 --- a/hugr/src/types.rs +++ b/hugr/src/types.rs @@ -38,7 +38,7 @@ pub type TypeName = SmolStr; pub type TypeNameRef = str; /// The kinds of edges in a HUGR, excluding Hierarchy. -#[derive(Clone, PartialEq, Debug, serde::Serialize, serde::Deserialize)] +#[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)] #[non_exhaustive] pub enum EdgeKind { /// Control edges of a CFG region. From db11b175354dcec6f205460d67d03132ea29e3a4 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sun, 26 May 2024 19:43:41 +0100 Subject: [PATCH 014/115] Make type_row! macro always produce a TypeRow, keep EMPTY_TYPEROW(_REF) --- hugr/src/macros.rs | 6 +++--- hugr/src/types.rs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/hugr/src/macros.rs b/hugr/src/macros.rs index e6b511daa..57ae23695 100644 --- a/hugr/src/macros.rs +++ b/hugr/src/macros.rs @@ -57,14 +57,14 @@ pub(crate) use impl_box_clone; macro_rules! type_row { () => { { - $crate::types::TypeRow::new() + $crate::types::TypeRow::::new() } }; ($($t:expr),+ $(,)?) => { { use $crate::types; static ROW: &[types::Type] = &[$($t),*]; - let row: types::TypeRow = ROW.into(); + let row: types::TypeRow = ROW.into(); row } }; @@ -72,7 +72,7 @@ macro_rules! type_row { { use $crate::types; static ROW: &[types::Type] = &[$t; $n]; - let row: types::TypeRow = ROW.into(); + let row: types::TypeRow = ROW.into(); row } }; diff --git a/hugr/src/types.rs b/hugr/src/types.rs index fe8ffd2ca..3d9188dc8 100644 --- a/hugr/src/types.rs +++ b/hugr/src/types.rs @@ -284,7 +284,7 @@ impl PartialEq> for Type { impl Type { /// An empty `TypeRow`. Provided here for convenience - pub const EMPTY_TYPEROW: TypeRow = type_row![]; + pub const EMPTY_TYPEROW: TypeRow = TypeRow::::new(); /// Unit type (empty tuple). pub const UNIT: Self = Self(TypeEnum::Sum(SumType::Unit { size: 1 }), TypeBound::Eq); From 2fa7feb6dddcfc7c5c5318ee0461b6c94057adfc Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sun, 26 May 2024 21:37:10 +0100 Subject: [PATCH 015/115] Parametrize new_tuple over , also new_sum (awkwardly) --- hugr/src/types.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/hugr/src/types.rs b/hugr/src/types.rs index 3d9188dc8..bc056983d 100644 --- a/hugr/src/types.rs +++ b/hugr/src/types.rs @@ -297,7 +297,7 @@ impl Type { /// Initialize a new tuple type by providing the elements. #[inline(always)] - pub fn new_tuple(types: impl Into>) -> Self { + pub fn new_tuple(types: impl Into>) -> Self { let row = types.into(); match row.len() { 0 => Self::UNIT, @@ -307,7 +307,10 @@ impl Type { /// Initialize a new sum type by providing the possible variant types. #[inline(always)] - pub fn new_sum(variants: impl IntoIterator>) -> Self where { + pub fn new_sum(variants: impl IntoIterator>) -> Self where { + let variants: Vec>> = variants.into_iter().map( + |t| t.into_owned().into_iter().map(Type::into_rv).collect() + ).collect(); Self::new(TypeEnum::Sum(SumType::new(variants))) } From 825e911c3bdc3a354851e4a91d94e278296b4691 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sun, 26 May 2024 21:37:37 +0100 Subject: [PATCH 016/115] Comment in leaf.rs re. Tag - could take some TypeRows --- hugr/src/ops/leaf.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/hugr/src/ops/leaf.rs b/hugr/src/ops/leaf.rs index 5e0edfea8..5b4cebe59 100644 --- a/hugr/src/ops/leaf.rs +++ b/hugr/src/ops/leaf.rs @@ -73,6 +73,8 @@ pub struct Tag { /// The variant to create. pub tag: usize, /// The variants of the sum type. + /// TODO this allows *none* of the variants to contain row variables, but + /// we could allow variants *other than the tagged one* to contain rowvars. pub variants: Vec, } From b83bee17ef9809bd7bc48e57345ad86e03a9aa83 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Thu, 30 May 2024 10:59:17 +0100 Subject: [PATCH 017/115] Double-parametrized PartialEq for TypeRow --- hugr-core/src/types/type_row.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/hugr-core/src/types/type_row.rs b/hugr-core/src/types/type_row.rs index 501caca72..9cf063603 100644 --- a/hugr-core/src/types/type_row.rs +++ b/hugr-core/src/types/type_row.rs @@ -16,7 +16,7 @@ use delegate::delegate; use itertools::Itertools; /// List of types, used for function signatures. -#[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Eq, Debug, serde::Serialize, serde::Deserialize)] #[non_exhaustive] #[serde(transparent)] pub struct TypeRow { @@ -24,6 +24,13 @@ pub struct TypeRow { types: Cow<'static, [Type]>, } +impl PartialEq> for TypeRow { + fn eq(&self, other: &TypeRow) -> bool { + self.types.len() == other.types.len() && + self.types.iter().zip(other.types.iter()).all(|(s,o)| s==o) + } +} + impl Display for TypeRow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_char('[')?; From 3ccef196946fb8c750cea47b2ac7e48fa5c4dadd Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Thu, 30 May 2024 11:10:09 +0100 Subject: [PATCH 018/115] (FunctionType,PolyFuncType,TypeRow)::validate for --- hugr-core/src/hugr/validate.rs | 4 ++-- hugr-core/src/types/poly_func.rs | 2 -- hugr-core/src/types/signature.rs | 4 ++-- hugr-core/src/types/type_row.rs | 20 +++++++++----------- 4 files changed, 13 insertions(+), 17 deletions(-) diff --git a/hugr-core/src/hugr/validate.rs b/hugr-core/src/hugr/validate.rs index 667245a03..2228da73c 100644 --- a/hugr-core/src/hugr/validate.rs +++ b/hugr-core/src/hugr/validate.rs @@ -301,10 +301,10 @@ impl<'a, 'b> ValidationContext<'a, 'b> { var_decls: &[TypeParam], ) -> Result<(), SignatureError> { match &port_kind { - EdgeKind::Value(ty) => ty.validate(false, self.extension_registry, var_decls), + EdgeKind::Value(ty) => ty.validate(self.extension_registry, var_decls), // Static edges must *not* refer to type variables declared by enclosing FuncDefns // as these are only types at runtime. (Note the choice of `allow_row_vars` as `false` is arbitrary here.) - EdgeKind::Const(ty) => ty.validate(false, self.extension_registry, &[]), + EdgeKind::Const(ty) => ty.validate(self.extension_registry, &[]), // Allow function "value" to have unknown arity. A Call node will have to provide // TypeArgs that produce a known arity, but a LoadFunction might pass the function // value ("function pointer") around without knowing how to call it. diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index 85b0f5a53..22eaf09c9 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -97,9 +97,7 @@ impl PolyFuncType { check_type_args(args, &self.params)?; Ok(self.body.substitute(&Substitution(args, ext_reg))) } -} -impl PolyFuncType { /// Validates this instance, checking that the types in the body are /// wellformed with respect to the registry, and the type variables declared. /// Allows both inputs and outputs to contain [RowVariable]s diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index b0ceb774b..a8452f252 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -84,9 +84,7 @@ impl FunctionType { pub fn output(&self) -> &TypeRow { &self.output } -} -impl FunctionType { pub(super) fn validate( &self, extension_registry: &ExtensionRegistry, @@ -97,7 +95,9 @@ impl FunctionType { .validate(extension_registry, var_decls)?; self.extension_reqs.validate(var_decls) } +} +impl FunctionType { /// If this FunctionType contains any row variables, return one. pub fn find_rowvar(&self) -> Option<(usize, TypeBound)> { self.input diff --git a/hugr-core/src/types/type_row.rs b/hugr-core/src/types/type_row.rs index 9cf063603..c1fe4ab9c 100644 --- a/hugr-core/src/types/type_row.rs +++ b/hugr-core/src/types/type_row.rs @@ -83,6 +83,15 @@ impl TypeRow { pub fn is_empty(&self) -> bool ; } } + + pub(super) fn validate( + &self, + exts: &ExtensionRegistry, + var_decls: &[TypeParam], + ) -> Result<(), SignatureError> { + self.iter() + .try_for_each(|t| t.validate(exts, var_decls)) + } } impl TypeRow { @@ -104,17 +113,6 @@ impl TypeRow { } } -impl TypeRow { - pub(super) fn validate( - &self, - exts: &ExtensionRegistry, - var_decls: &[TypeParam], - ) -> Result<(), SignatureError> { - self.iter() - .try_for_each(|t| t.validate(exts, var_decls)) - } -} - impl From for TypeRow { fn from(value: TypeRow) -> Self { Self::from(value.into_owned().into_iter().map_into().collect::>>()) From c9b80f9d68fe946caa4db16115d79b72c0fcbcfe Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Thu, 30 May 2024 11:11:39 +0100 Subject: [PATCH 019/115] sum_with_error: fix with 2*.into --- hugr-core/src/extension/prelude.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hugr-core/src/extension/prelude.rs b/hugr-core/src/extension/prelude.rs index 89719a6c0..9d701449b 100644 --- a/hugr-core/src/extension/prelude.rs +++ b/hugr-core/src/extension/prelude.rs @@ -268,7 +268,7 @@ pub const ERROR_TYPE_NAME: TypeName = TypeName::new_inline("error"); /// Return a Sum type with the first variant as the given type and the second an Error. pub fn sum_with_error(ty: Type) -> SumType { - SumType::new([vec![ty], vec![ERROR_TYPE]]) + SumType::new([vec![ty.into()], vec![ERROR_TYPE.into()]]) } #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] From 5849a4f7cc62cfb927c042ab3c804f6050909328 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Thu, 30 May 2024 11:35:48 +0100 Subject: [PATCH 020/115] TypeRow: drop false->true Into, add TypeRow::into_rv() -> TypeRow --- hugr-core/src/types/signature.rs | 2 +- hugr-core/src/types/type_row.rs | 15 +++++++++++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index a8452f252..c355c1701 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -249,7 +249,7 @@ impl TryFrom for Signature { impl From for FunctionType { fn from(value: Signature) -> Self { - Self::new(value.input, value.output).with_extension_delta(value.extension_reqs) + Self::new(value.input.into_rv(), value.output.into_rv()).with_extension_delta(value.extension_reqs) } } diff --git a/hugr-core/src/types/type_row.rs b/hugr-core/src/types/type_row.rs index c1fe4ab9c..f7e82e1f8 100644 --- a/hugr-core/src/types/type_row.rs +++ b/hugr-core/src/types/type_row.rs @@ -92,6 +92,10 @@ impl TypeRow { self.iter() .try_for_each(|t| t.validate(exts, var_decls)) } + + pub fn into_rv(self) -> TypeRow { + TypeRow::from(self.types.into_iter().cloned().map(Type::into_rv).collect::>()) + } } impl TypeRow { @@ -113,11 +117,18 @@ impl TypeRow { } } -impl From for TypeRow { +/*impl From for TypeRow { fn from(value: TypeRow) -> Self { Self::from(value.into_owned().into_iter().map_into().collect::>>()) } -} +}*/ + +/*impl Into]>> for TypeRow { + fn into(self) -> Cow<'static, [Type]> { + let tr = self.types.into_iter().cloned().map(|t| t.into()).collect(); + Cow::Owned(tr) + } +}*/ impl TryFrom> for TypeRow { type Error = SignatureError; From 0e3691cf0ec12bd8cd9a6a364809477a1a463065 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Thu, 30 May 2024 11:54:40 +0100 Subject: [PATCH 021/115] Signature -> SignatureFunc --- hugr-core/src/extension/op_def.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/hugr-core/src/extension/op_def.rs b/hugr-core/src/extension/op_def.rs index 35897b02e..f6f3ea33d 100644 --- a/hugr-core/src/extension/op_def.rs +++ b/hugr-core/src/extension/op_def.rs @@ -201,6 +201,13 @@ impl From for SignatureFunc { } } +impl From for SignatureFunc { + fn from(value: Signature) -> Self { + let value: FunctionType = value.into(); + Self::TypeScheme(CustomValidator::from_polyfunc(value)) + } +} + impl From for SignatureFunc { fn from(v: CustomValidator) -> Self { Self::TypeScheme(v) From d3ccd7974ac0ba709353a6b65762087218251c93 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Thu, 30 May 2024 11:55:15 +0100 Subject: [PATCH 022/115] logic.rs: add extra TypeRow::from --- hugr-core/src/std_extensions/logic.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/hugr-core/src/std_extensions/logic.rs b/hugr-core/src/std_extensions/logic.rs index d6e51811f..7f62b129b 100644 --- a/hugr-core/src/std_extensions/logic.rs +++ b/hugr-core/src/std_extensions/logic.rs @@ -5,6 +5,7 @@ use strum_macros::{EnumIter, EnumString, IntoStaticStr}; use crate::extension::{ConstFold, ConstFoldResult}; use crate::ops::constant::ValueName; use crate::ops::{OpName, Value}; +use crate::types::TypeRow; use crate::{ extension::{ prelude::BOOL_T, @@ -161,8 +162,8 @@ fn logic_op_sig() -> impl SignatureFromArgs { let [TypeArg::BoundedNat { n }] = *arg_values else { return Err(SignatureError::InvalidTypeArgs); }; - let var_arg_row = vec![BOOL_T; n as usize]; - Ok(FunctionType::new(var_arg_row, vec![BOOL_T]).into()) + let var_arg_row = TypeRow::from(vec![BOOL_T; n as usize]); + Ok(FunctionType::new(var_arg_row.into_rv(), vec![BOOL_T.into()]).into()) } fn static_params(&self) -> &[TypeParam] { From c2c0cd97a653c85d0562f5a367b8998fb44f0128 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Thu, 30 May 2024 11:55:37 +0100 Subject: [PATCH 023/115] Add SumTypeError::VariantNotConcrete --- hugr-core/src/types/check.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/hugr-core/src/types/check.rs b/hugr-core/src/types/check.rs index 174ff817d..3e7dda1f7 100644 --- a/hugr-core/src/types/check.rs +++ b/hugr-core/src/types/check.rs @@ -2,8 +2,8 @@ use thiserror::Error; -use super::Type; -use crate::ops::Value; +use super::{type_param::TypeParam, Type, TypeRow}; +use crate::{extension::SignatureError, ops::Value}; /// Errors that arise from typechecking constants #[derive(Clone, Debug, PartialEq, Error)] @@ -21,6 +21,14 @@ pub enum SumTypeError { /// The value that was found. found: Value, }, + /// The type of the variant we were trying to convert into contained type variables + #[error("Sum variant #{tag} contained a variable #{varidx}")] + VariantNotConcrete { + /// The variant index + tag: usize, + /// The index (identifier) of the type-variable + varidx: usize, + }, /// The length of the sum value doesn't match the length of the variant of /// the sum type. #[error("Sum variant #{tag} should have length {expected}, but has length {found}")] @@ -60,6 +68,9 @@ impl super::SumType { tag, num_variants: self.num_variants(), })?; + let variant: TypeRow = variant.clone().try_into().map_err(|e| + {let SignatureError::RowVarWhereTypeExpected {idx} = e else {panic!("Unexpected error")}; + SumTypeError::VariantNotConcrete { tag, varidx: idx }})?; if variant.len() != val.len() { Err(SumTypeError::WrongVariantLength { From eefc35d6faf63efa423dac30192f9f30da9c3601 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Thu, 30 May 2024 11:55:46 +0100 Subject: [PATCH 024/115] fmt --- hugr-core/src/builder/cfg.rs | 5 ++- hugr-core/src/extension/op_def.rs | 7 ++-- hugr-core/src/hugr/serialize/test.rs | 2 +- hugr-core/src/ops/controlflow.rs | 12 ++++--- hugr-core/src/types.rs | 44 +++++++++++++------------ hugr-core/src/types/check.rs | 9 ++++-- hugr-core/src/types/serialize.rs | 16 +++++++--- hugr-core/src/types/signature.rs | 12 ++++--- hugr-core/src/types/type_param.rs | 8 ++--- hugr-core/src/types/type_row.rs | 48 ++++++++++++++++++---------- 10 files changed, 96 insertions(+), 67 deletions(-) diff --git a/hugr-core/src/builder/cfg.rs b/hugr-core/src/builder/cfg.rs index 6fa07c542..c8e1aa5cd 100644 --- a/hugr-core/src/builder/cfg.rs +++ b/hugr-core/src/builder/cfg.rs @@ -5,12 +5,15 @@ use super::{ BasicBlockID, BuildError, CfgID, Container, Dataflow, HugrBuilder, Wire, }; -use crate::{ops::{self, handle::NodeHandle, DataflowBlock, DataflowParent, ExitBlock, OpType}, types::Signature}; use crate::{ extension::{ExtensionRegistry, ExtensionSet}, types::FunctionType, }; use crate::{hugr::views::HugrView, types::TypeRow}; +use crate::{ + ops::{self, handle::NodeHandle, DataflowBlock, DataflowParent, ExitBlock, OpType}, + types::Signature, +}; use crate::Node; use crate::{ diff --git a/hugr-core/src/extension/op_def.rs b/hugr-core/src/extension/op_def.rs index f6f3ea33d..2ec90c7e7 100644 --- a/hugr-core/src/extension/op_def.rs +++ b/hugr-core/src/extension/op_def.rs @@ -34,10 +34,7 @@ pub trait CustomSignatureFunc: Send + Sync { pub trait SignatureFromArgs: Send + Sync { /// Compute signature of node given /// values for the type parameters. - fn compute_signature( - &self, - arg_values: &[TypeArg], - ) -> Result; + fn compute_signature(&self, arg_values: &[TypeArg]) -> Result; /// The declared type parameters which require values in order for signature to /// be computed. fn static_params(&self) -> &[TypeParam]; @@ -500,7 +497,7 @@ pub(super) mod test { use crate::ops::{CustomOp, OpName}; use crate::std_extensions::collections::{EXTENSION, LIST_TYPENAME}; use crate::types::type_param::{TypeArgError, TypeParam}; - use crate::types::{FunctionType, PolyFuncType, TypeArg, TypeBound, Type}; + use crate::types::{FunctionType, PolyFuncType, Type, TypeArg, TypeBound}; use crate::{const_extension_ids, Extension}; const_extension_ids! { diff --git a/hugr-core/src/hugr/serialize/test.rs b/hugr-core/src/hugr/serialize/test.rs index bdce7da89..b386b3412 100644 --- a/hugr-core/src/hugr/serialize/test.rs +++ b/hugr-core/src/hugr/serialize/test.rs @@ -447,7 +447,7 @@ fn polyfunctype2() -> PolyFuncType { [TypeParam::new_list(TypeBound::Any)], FunctionType::new_endo(Type::new_tuple(Type::new_row_var_use(0, TypeBound::Any)))))] #[case(polyfunctype2())] -fn roundtrip_polyfunctype(#[case] poly_func_type: PolyFuncType) { +fn roundtrip_polyfunctype(#[case] poly_func_type: PolyFuncType) { check_testing_roundtrip(poly_func_type) } diff --git a/hugr-core/src/ops/controlflow.rs b/hugr-core/src/ops/controlflow.rs index 0c16dc351..297954c2c 100644 --- a/hugr-core/src/ops/controlflow.rs +++ b/hugr-core/src/ops/controlflow.rs @@ -39,7 +39,10 @@ impl DataflowOpTrait for TailLoop { impl TailLoop { /// Build the output TypeRow of the child graph of a TailLoop node. pub(crate) fn body_output_row(&self) -> TypeRow { - let sum_type = Type::new_sum([self.just_inputs.clone().into(), self.just_outputs.clone().into()]); + let sum_type = Type::new_sum([ + self.just_inputs.clone().into(), + self.just_outputs.clone().into(), + ]); let mut outputs = vec![sum_type]; outputs.extend_from_slice(&self.rest); outputs.into() @@ -75,9 +78,10 @@ impl DataflowOpTrait for Conditional { fn signature(&self) -> Signature { let mut inputs = self.other_inputs.clone(); - inputs - .to_mut() - .insert(0, Type::new_sum(self.sum_rows.iter().map(|r| r.clone().into()))); + inputs.to_mut().insert( + 0, + Type::new_sum(self.sum_rows.iter().map(|r| r.clone().into())), + ); FunctionType::new(inputs, self.outputs.clone()) .with_extension_delta(self.extension_delta.clone()) } diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index bc056983d..bc7fa2b6c 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -187,7 +187,7 @@ impl SumType { } } -impl From for Type { +impl From for Type { fn from(sum: SumType) -> Self { match sum { SumType::Unit { size } => Type::new_unit_sum(size), @@ -249,11 +249,12 @@ impl TypeEnum { } } -#[derive( - Clone, Debug, Eq, derive_more::Display, serde::Serialize, serde::Deserialize, -)] +#[derive(Clone, Debug, Eq, derive_more::Display, serde::Serialize, serde::Deserialize)] #[display(fmt = "{}", "_0")] -#[serde(into = "serialize::SerSimpleType", try_from = "serialize::SerSimpleType")] +#[serde( + into = "serialize::SerSimpleType", + try_from = "serialize::SerSimpleType" +)] /// A HUGR type - the valid types of [EdgeKind::Value] and [EdgeKind::Const] edges. /// Such an edge is valid if the ports on either end agree on the [Type]. /// Types have an optional [TypeBound] which places limits on the valid @@ -274,15 +275,15 @@ impl TypeEnum { /// let func_type = Type::new_function(FunctionType::new_endo(vec![])); /// assert_eq!(func_type.least_upper_bound(), TypeBound::Copyable); /// ``` -pub struct Type(TypeEnum, TypeBound); +pub struct Type(TypeEnum, TypeBound); -impl PartialEq> for Type { +impl PartialEq> for Type { fn eq(&self, other: &Type) -> bool { self.0 == other.0 && self.1 == other.1 } } -impl Type { +impl Type { /// An empty `TypeRow`. Provided here for convenience pub const EMPTY_TYPEROW: TypeRow = TypeRow::::new(); /// Unit type (empty tuple). @@ -297,7 +298,7 @@ impl Type { /// Initialize a new tuple type by providing the elements. #[inline(always)] - pub fn new_tuple(types: impl Into>) -> Self { + pub fn new_tuple(types: impl Into>) -> Self { let row = types.into(); match row.len() { 0 => Self::UNIT, @@ -307,10 +308,12 @@ impl Type { /// Initialize a new sum type by providing the possible variant types. #[inline(always)] - pub fn new_sum(variants: impl IntoIterator>) -> Self where { - let variants: Vec>> = variants.into_iter().map( - |t| t.into_owned().into_iter().map(Type::into_rv).collect() - ).collect(); + pub fn new_sum(variants: impl IntoIterator>) -> Self where + { + let variants: Vec>> = variants + .into_iter() + .map(|t| t.into_owned().into_iter().map(Type::into_rv).collect()) + .collect(); Self::new(TypeEnum::Sum(SumType::new(variants))) } @@ -413,7 +416,7 @@ impl Type { TypeEnum::RowVariable(idx, bound) => { assert!(RV); let res = t.apply_rowvar(*idx, *bound); // these are Type's - // We need Types, so use try_into_(). Since we know RV==true, this cannot fail. + // We need Types, so use try_into_(). Since we know RV==true, this cannot fail. res.into_iter().map(|t| t.try_into_().unwrap()).collect() } TypeEnum::Alias(_) | TypeEnum::Sum(SumType::Unit { .. }) => vec![self.clone()], @@ -445,7 +448,7 @@ impl Type { pub fn is_row_var(&self) -> bool { matches!(self.0, TypeEnum::RowVariable(_, _)) } - + /// New use (occurrence) of the row variable with specified index. /// `bound` must match that with which the variable was declared /// (i.e. as a [TypeParam::List]` of a `[TypeParam::Type]` of that bound). @@ -464,13 +467,13 @@ impl Type { // ====== Conversions ====== impl Type { - fn into_(self) -> Type { + fn into_(self) -> Type { Type(self.0, self.1) } } impl Type { - fn try_into_(self) -> Result, SignatureError> { + fn try_into_(self) -> Result, SignatureError> { if !RV { if let TypeEnum::RowVariable(idx, _) = self.0 { return Err(SignatureError::RowVarWhereTypeExpected { idx }); @@ -480,11 +483,11 @@ impl Type { } } -impl Type { +impl Type { fn try_into_no_rv(self) -> Result, SignatureError> { if let TypeEnum::RowVariable(idx, _) = self.0 { assert!(RV); - return Err(SignatureError::RowVarWhereTypeExpected { idx }) + return Err(SignatureError::RowVarWhereTypeExpected { idx }); } Ok(Type(self.0, self.1)) } @@ -507,7 +510,6 @@ impl TryFrom> for Type { } } - /// Details a replacement of type variables with a finite list of known values. /// (Variables out of the range of the list will result in a panic) pub(crate) struct Substitution<'a>(&'a [TypeArg], &'a ExtensionRegistry); @@ -602,7 +604,7 @@ pub(crate) mod test { } #[rstest::rstest] - fn sum_construct() { + fn sum_construct() { let pred1 = Type::new_sum([Type::EMPTY_TYPEROW, Type::EMPTY_TYPEROW]); let pred2 = Type::new_unit_sum(2); diff --git a/hugr-core/src/types/check.rs b/hugr-core/src/types/check.rs index 3e7dda1f7..61d7641e3 100644 --- a/hugr-core/src/types/check.rs +++ b/hugr-core/src/types/check.rs @@ -68,9 +68,12 @@ impl super::SumType { tag, num_variants: self.num_variants(), })?; - let variant: TypeRow = variant.clone().try_into().map_err(|e| - {let SignatureError::RowVarWhereTypeExpected {idx} = e else {panic!("Unexpected error")}; - SumTypeError::VariantNotConcrete { tag, varidx: idx }})?; + let variant: TypeRow = variant.clone().try_into().map_err(|e| { + let SignatureError::RowVarWhereTypeExpected { idx } = e else { + panic!("Unexpected error") + }; + SumTypeError::VariantNotConcrete { tag, varidx: idx } + })?; if variant.len() != val.len() { Err(SumTypeError::WrongVariantLength { diff --git a/hugr-core/src/types/serialize.rs b/hugr-core/src/types/serialize.rs index a82e653b9..e0b9e1f48 100644 --- a/hugr-core/src/types/serialize.rs +++ b/hugr-core/src/types/serialize.rs @@ -20,10 +20,14 @@ pub(super) enum SerSimpleType { R { i: usize, b: TypeBound }, } -impl From> for SerSimpleType { +impl From> for SerSimpleType { fn from(value: Type) -> Self { - if value == QB_T { return SerSimpleType::Q }; - if value == USIZE_T { return SerSimpleType::I }; + if value == QB_T { + return SerSimpleType::Q; + }; + if value == USIZE_T { + return SerSimpleType::I; + }; match value.0 { TypeEnum::Extension(o) => SerSimpleType::Opaque(o), TypeEnum::Alias(a) => SerSimpleType::Alias(a), @@ -35,7 +39,7 @@ impl From> for SerSimpleType { } } -impl TryFrom for Type { +impl TryFrom for Type { type Error = SignatureError; fn try_from(value: SerSimpleType) -> Result { Ok(match value { @@ -50,7 +54,9 @@ impl TryFrom for Type { SerSimpleType::Alias(a) => Type::new_alias(a), SerSimpleType::V { i, b } => Type::new_var_use(i, b), // We can't use new_row_var because that returns Type not Type. - value@SerSimpleType::R { i, b } => Type::new(TypeEnum::RowVariable(i, b)).try_into_()? + value @ SerSimpleType::R { i, b } => { + Type::new(TypeEnum::RowVariable(i, b)).try_into_()? + } }) } } diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index c355c1701..0c160c458 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -91,8 +91,7 @@ impl FunctionType { var_decls: &[TypeParam], ) -> Result<(), SignatureError> { self.input.validate(extension_registry, var_decls)?; - self.output - .validate(extension_registry, var_decls)?; + self.output.validate(extension_registry, var_decls)?; self.extension_reqs.validate(var_decls) } } @@ -107,7 +106,7 @@ impl FunctionType { TypeEnum::RowVariable(idx, bound) => Some((idx, bound)), _ => None, }) - } + } } impl Signature { @@ -249,13 +248,16 @@ impl TryFrom for Signature { impl From for FunctionType { fn from(value: Signature) -> Self { - Self::new(value.input.into_rv(), value.output.into_rv()).with_extension_delta(value.extension_reqs) + Self::new(value.input.into_rv(), value.output.into_rv()) + .with_extension_delta(value.extension_reqs) } } impl PartialEq for Signature { fn eq(&self, other: &FunctionType) -> bool { - self.input == other.input && self.output == other.output && self.extension_reqs == other.extension_reqs + self.input == other.input + && self.output == other.output + && self.extension_reqs == other.extension_reqs } } diff --git a/hugr-core/src/types/type_param.rs b/hugr-core/src/types/type_param.rs index c16a34ded..d81525d18 100644 --- a/hugr-core/src/types/type_param.rs +++ b/hugr-core/src/types/type_param.rs @@ -269,7 +269,8 @@ impl TypeArg { TypeArg::Variable { v: TypeArgVariable { idx, cached_decl }, } => { - assert!(!matches!(cached_decl, TypeParam::Type {..}), + assert!( + !matches!(cached_decl, TypeParam::Type { .. }), "Malformed TypeArg::Variable {} - should be inconstructible", cached_decl ); @@ -371,9 +372,7 @@ pub fn check_type_arg(arg: &TypeArg, param: &TypeParam) -> Result<(), TypeArgErr Ok(()) } (TypeArg::Sequence { elems }, TypeParam::List { param }) => { - elems.iter().try_for_each(|arg| { - check_type_arg(arg, param) - }) + elems.iter().try_for_each(|arg| check_type_arg(arg, param)) } // Also allow a single "Type" to be used for a List *only* if the Type is a row variable // (i.e., it's not really a Type, it's multiple Types) @@ -383,7 +382,6 @@ pub fn check_type_arg(arg: &TypeArg, param: &TypeParam) -> Result<(), TypeArgErr { Ok(()) }*/ - (TypeArg::Sequence { elems: items }, TypeParam::Tuple { params: types }) => { if items.len() != types.len() { Err(TypeArgError::WrongNumberTuple(items.len(), types.len())) diff --git a/hugr-core/src/types/type_row.rs b/hugr-core/src/types/type_row.rs index f7e82e1f8..cb111eeb3 100644 --- a/hugr-core/src/types/type_row.rs +++ b/hugr-core/src/types/type_row.rs @@ -19,19 +19,23 @@ use itertools::Itertools; #[derive(Clone, Eq, Debug, serde::Serialize, serde::Deserialize)] #[non_exhaustive] #[serde(transparent)] -pub struct TypeRow { +pub struct TypeRow { /// The datatypes in the row. types: Cow<'static, [Type]>, } -impl PartialEq> for TypeRow { +impl PartialEq> for TypeRow { fn eq(&self, other: &TypeRow) -> bool { - self.types.len() == other.types.len() && - self.types.iter().zip(other.types.iter()).all(|(s,o)| s==o) + self.types.len() == other.types.len() + && self + .types + .iter() + .zip(other.types.iter()) + .all(|(s, o)| s == o) } } -impl Display for TypeRow { +impl Display for TypeRow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_char('[')?; display_list(self.types.as_ref(), f)?; @@ -39,7 +43,7 @@ impl Display for TypeRow { } } -impl TypeRow { +impl TypeRow { /// Create a new empty row. pub const fn new() -> Self { Self { @@ -61,8 +65,7 @@ impl TypeRow { /// For `TypeRow`, note this may change the length of the row. /// For `TypeRow`, guaranteed not to change the length of the row. pub(super) fn substitute(&self, s: &Substitution) -> Self { - self - .iter() + self.iter() .flat_map(|ty| ty.subst_vec(s)) .collect::>() .into() @@ -89,12 +92,17 @@ impl TypeRow { exts: &ExtensionRegistry, var_decls: &[TypeParam], ) -> Result<(), SignatureError> { - self.iter() - .try_for_each(|t| t.validate(exts, var_decls)) + self.iter().try_for_each(|t| t.validate(exts, var_decls)) } pub fn into_rv(self) -> TypeRow { - TypeRow::from(self.types.into_iter().cloned().map(Type::into_rv).collect::>()) + TypeRow::from( + self.types + .into_iter() + .cloned() + .map(Type::into_rv) + .collect::>(), + ) } } @@ -134,17 +142,23 @@ impl TryFrom> for TypeRow { type Error = SignatureError; fn try_from(value: TypeRow) -> Result { - Ok(Self::from(value.into_owned().into_iter().map(|t| t.try_into()).collect::,_>>()?)) + Ok(Self::from( + value + .into_owned() + .into_iter() + .map(|t| t.try_into()) + .collect::, _>>()?, + )) } } -impl Default for TypeRow { +impl Default for TypeRow { fn default() -> Self { Self::new() } } -impl From for TypeRow +impl From for TypeRow where F: Into]>>, { @@ -155,7 +169,7 @@ where } } -impl From> for TypeRow { +impl From> for TypeRow { fn from(t: Type) -> Self { Self { types: vec![t].into(), @@ -163,7 +177,7 @@ impl From> for TypeRow { } } -impl Deref for TypeRow { +impl Deref for TypeRow { type Target = [Type]; fn deref(&self) -> &Self::Target { @@ -171,7 +185,7 @@ impl Deref for TypeRow { } } -impl DerefMut for TypeRow { +impl DerefMut for TypeRow { fn deref_mut(&mut self) -> &mut Self::Target { self.types.to_mut() } From a22e5a14ae47e6aacc304834b6dd3f55e53c2614 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Thu, 30 May 2024 11:57:24 +0100 Subject: [PATCH 025/115] Various clippy's --- hugr-core/src/builder/cfg.rs | 5 +---- hugr-core/src/builder/dataflow.rs | 2 +- hugr-core/src/extension.rs | 2 +- hugr-core/src/hugr/validate.rs | 2 +- hugr-core/src/hugr/views/sibling_subgraph.rs | 1 - hugr-core/src/ops.rs | 2 +- hugr-core/src/ops/controlflow.rs | 14 +++++--------- hugr-core/src/ops/custom.rs | 2 +- hugr-core/src/ops/module.rs | 2 +- hugr-core/src/types.rs | 1 - hugr-core/src/types/check.rs | 2 +- hugr-core/src/types/serialize.rs | 4 +--- hugr-core/src/types/type_row.rs | 2 +- hugr-passes/src/const_fold.rs | 4 ++-- 14 files changed, 17 insertions(+), 28 deletions(-) diff --git a/hugr-core/src/builder/cfg.rs b/hugr-core/src/builder/cfg.rs index c8e1aa5cd..847813abc 100644 --- a/hugr-core/src/builder/cfg.rs +++ b/hugr-core/src/builder/cfg.rs @@ -5,10 +5,7 @@ use super::{ BasicBlockID, BuildError, CfgID, Container, Dataflow, HugrBuilder, Wire, }; -use crate::{ - extension::{ExtensionRegistry, ExtensionSet}, - types::FunctionType, -}; +use crate::extension::{ExtensionRegistry, ExtensionSet}; use crate::{hugr::views::HugrView, types::TypeRow}; use crate::{ ops::{self, handle::NodeHandle, DataflowBlock, DataflowParent, ExitBlock, OpType}, diff --git a/hugr-core/src/builder/dataflow.rs b/hugr-core/src/builder/dataflow.rs index cfd21ff97..ec9c087a7 100644 --- a/hugr-core/src/builder/dataflow.rs +++ b/hugr-core/src/builder/dataflow.rs @@ -7,7 +7,7 @@ use std::marker::PhantomData; use crate::hugr::{HugrView, NodeType, ValidationError}; use crate::ops; -use crate::types::{FunctionType, PolyFuncType, Signature}; +use crate::types::{PolyFuncType, Signature}; use crate::extension::{ExtensionRegistry, ExtensionSet}; use crate::Node; diff --git a/hugr-core/src/extension.rs b/hugr-core/src/extension.rs index 01d54f436..c645b5f21 100644 --- a/hugr-core/src/extension.rs +++ b/hugr-core/src/extension.rs @@ -17,8 +17,8 @@ use crate::ops::custom::{ExtensionOp, OpaqueOp}; use crate::ops::{self, OpName, OpNameRef}; use crate::types::type_param::{TypeArg, TypeArgError, TypeParam}; use crate::types::Signature; +use crate::types::TypeNameRef; use crate::types::{check_typevar_decl, CustomType, Substitution, TypeBound, TypeName}; -use crate::types::{FunctionType, TypeNameRef}; #[allow(dead_code)] mod infer; diff --git a/hugr-core/src/hugr/validate.rs b/hugr-core/src/hugr/validate.rs index 2228da73c..9eac95556 100644 --- a/hugr-core/src/hugr/validate.rs +++ b/hugr-core/src/hugr/validate.rs @@ -20,7 +20,7 @@ use crate::ops::custom::{resolve_opaque_op, CustomOp}; use crate::ops::validate::{ChildrenEdgeData, ChildrenValidationError, EdgeValidationError}; use crate::ops::{FuncDefn, OpTag, OpTrait, OpType, ValidateOp}; use crate::types::type_param::TypeParam; -use crate::types::{EdgeKind, FunctionType}; +use crate::types::EdgeKind; use crate::{Direction, Hugr, Node, Port}; use super::views::{HierarchyView, HugrView, SiblingGraph}; diff --git a/hugr-core/src/hugr/views/sibling_subgraph.rs b/hugr-core/src/hugr/views/sibling_subgraph.rs index 1b6a7de97..0203f6a48 100644 --- a/hugr-core/src/hugr/views/sibling_subgraph.rs +++ b/hugr-core/src/hugr/views/sibling_subgraph.rs @@ -18,7 +18,6 @@ use portgraph::{view::Subgraph, Direction, PortView}; use thiserror::Error; use crate::builder::{Container, FunctionBuilder}; -use crate::extension::SignatureError; use crate::hugr::{HugrMut, HugrView, RootTagged}; use crate::ops::dataflow::DataflowOpTrait; use crate::ops::handle::{ContainerHandle, DataflowOpID}; diff --git a/hugr-core/src/ops.rs b/hugr-core/src/ops.rs index 2299eb1e1..668216de7 100644 --- a/hugr-core/src/ops.rs +++ b/hugr-core/src/ops.rs @@ -10,7 +10,7 @@ pub mod module; pub mod tag; pub mod validate; use crate::extension::ExtensionSet; -use crate::types::{EdgeKind, FunctionType, Signature}; +use crate::types::{EdgeKind, Signature}; use crate::{Direction, OutgoingPort, Port}; use crate::{IncomingPort, PortIndex}; use paste::paste; diff --git a/hugr-core/src/ops/controlflow.rs b/hugr-core/src/ops/controlflow.rs index 297954c2c..e109961d7 100644 --- a/hugr-core/src/ops/controlflow.rs +++ b/hugr-core/src/ops/controlflow.rs @@ -39,10 +39,7 @@ impl DataflowOpTrait for TailLoop { impl TailLoop { /// Build the output TypeRow of the child graph of a TailLoop node. pub(crate) fn body_output_row(&self) -> TypeRow { - let sum_type = Type::new_sum([ - self.just_inputs.clone().into(), - self.just_outputs.clone().into(), - ]); + let sum_type = Type::new_sum([self.just_inputs.clone(), self.just_outputs.clone()]); let mut outputs = vec![sum_type]; outputs.extend_from_slice(&self.rest); outputs.into() @@ -78,10 +75,9 @@ impl DataflowOpTrait for Conditional { fn signature(&self) -> Signature { let mut inputs = self.other_inputs.clone(); - inputs.to_mut().insert( - 0, - Type::new_sum(self.sum_rows.iter().map(|r| r.clone().into())), - ); + inputs + .to_mut() + .insert(0, Type::new_sum(self.sum_rows.iter().cloned())); FunctionType::new(inputs, self.outputs.clone()) .with_extension_delta(self.extension_delta.clone()) } @@ -159,7 +155,7 @@ impl StaticTag for ExitBlock { impl DataflowParent for DataflowBlock { fn inner_signature(&self) -> Signature { // The node outputs a Sum before the data outputs of the block node - let sum_type = Type::new_sum(self.sum_rows.iter().map(|r| r.clone().into())); + let sum_type = Type::new_sum(self.sum_rows.iter().cloned()); let mut node_outputs = vec![sum_type]; node_outputs.extend_from_slice(&self.other_outputs); FunctionType::new(self.inputs.clone(), TypeRow::from(node_outputs)) diff --git a/hugr-core/src/ops/custom.rs b/hugr-core/src/ops/custom.rs index 9ae370ee1..47b64893f 100644 --- a/hugr-core/src/ops/custom.rs +++ b/hugr-core/src/ops/custom.rs @@ -13,7 +13,7 @@ use { use crate::extension::{ConstFoldResult, ExtensionId, ExtensionRegistry, OpDef, SignatureError}; use crate::hugr::internal::HugrMutInternals; use crate::hugr::{HugrView, NodeType}; -use crate::types::{type_param::TypeArg, FunctionType}; +use crate::types::type_param::TypeArg; use crate::types::{EdgeKind, Signature}; use crate::{ops, Hugr, IncomingPort, Node}; diff --git a/hugr-core/src/ops/module.rs b/hugr-core/src/ops/module.rs index 725ac0819..c8f99c137 100644 --- a/hugr-core/src/ops/module.rs +++ b/hugr-core/src/ops/module.rs @@ -7,7 +7,7 @@ use { ::proptest_derive::Arbitrary, }; -use crate::types::{EdgeKind, FunctionType, PolyFuncType, Signature}; +use crate::types::{EdgeKind, PolyFuncType, Signature}; use crate::types::{Type, TypeBound}; use super::dataflow::DataflowParent; diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index bc7fa2b6c..d3266d5da 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -27,7 +27,6 @@ use {crate::proptest::RecursionDepth, ::proptest::prelude::*, proptest_derive::A use crate::extension::{ExtensionRegistry, SignatureError}; use crate::ops::AliasDecl; -use crate::type_row; use self::type_param::TypeParam; diff --git a/hugr-core/src/types/check.rs b/hugr-core/src/types/check.rs index 61d7641e3..95343c0fc 100644 --- a/hugr-core/src/types/check.rs +++ b/hugr-core/src/types/check.rs @@ -2,7 +2,7 @@ use thiserror::Error; -use super::{type_param::TypeParam, Type, TypeRow}; +use super::{Type, TypeRow}; use crate::{extension::SignatureError, ops::Value}; /// Errors that arise from typechecking constants diff --git a/hugr-core/src/types/serialize.rs b/hugr-core/src/types/serialize.rs index e0b9e1f48..4c25dd94b 100644 --- a/hugr-core/src/types/serialize.rs +++ b/hugr-core/src/types/serialize.rs @@ -54,9 +54,7 @@ impl TryFrom for Type { SerSimpleType::Alias(a) => Type::new_alias(a), SerSimpleType::V { i, b } => Type::new_var_use(i, b), // We can't use new_row_var because that returns Type not Type. - value @ SerSimpleType::R { i, b } => { - Type::new(TypeEnum::RowVariable(i, b)).try_into_()? - } + SerSimpleType::R { i, b } => Type::new(TypeEnum::RowVariable(i, b)).try_into_()?, }) } } diff --git a/hugr-core/src/types/type_row.rs b/hugr-core/src/types/type_row.rs index cb111eeb3..268450f34 100644 --- a/hugr-core/src/types/type_row.rs +++ b/hugr-core/src/types/type_row.rs @@ -98,7 +98,7 @@ impl TypeRow { pub fn into_rv(self) -> TypeRow { TypeRow::from( self.types - .into_iter() + .iter() .cloned() .map(Type::into_rv) .collect::>(), diff --git a/hugr-passes/src/const_fold.rs b/hugr-passes/src/const_fold.rs index bead78c50..82a3dd83e 100644 --- a/hugr-passes/src/const_fold.rs +++ b/hugr-passes/src/const_fold.rs @@ -6,7 +6,7 @@ use itertools::Itertools; use thiserror::Error; use hugr_core::hugr::{SimpleReplacementError, ValidationError}; -use hugr_core::types::SumType; +use hugr_core::types::{SumType, TypeRow}; use hugr_core::Direction; use hugr_core::{ builder::{DFGBuilder, Dataflow, DataflowHugr}, @@ -64,7 +64,7 @@ pub fn fold_leaf_op(op: &OpType, consts: &[(IncomingPort, Value)]) -> ConstFoldR OpType::Tag(t) => out_row([Value::sum( t.tag, consts.iter().map(|(_, konst)| konst.clone()), - SumType::new(t.variants.clone()), + SumType::new(t.variants.iter().cloned().map(TypeRow::into_rv)), ) .unwrap()]), OpType::CustomOp(op) => { From 15a1bbd98689472ac6d0444740f6e2eba3a38820 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Thu, 30 May 2024 12:07:45 +0100 Subject: [PATCH 026/115] Rename Type::substitute(=>substitute1), Type::subst_vec(=>substitute) --- hugr-core/src/types.rs | 10 +++------- hugr-core/src/types/type_param.rs | 2 +- hugr-core/src/types/type_row.rs | 2 +- 3 files changed, 5 insertions(+), 9 deletions(-) diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index d3266d5da..493c392b0 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -410,7 +410,7 @@ impl Type { /// * If [Type::validate]`(false)` returns successfully, this method will return a Vec containing exactly one type /// * If [Type::validate]`(false)` fails, but `(true)` succeeds, this method may (depending on structure of self) /// return a Vec containing any number of [Type]s. These may (or not) pass [Type::validate] - fn subst_vec(&self, t: &Substitution) -> Vec { + fn substitute(&self, t: &Substitution) -> Vec { match &self.0 { TypeEnum::RowVariable(idx, bound) => { assert!(RV); @@ -435,8 +435,8 @@ impl Type { } impl Type { - fn substitute(&self, s: &Substitution) -> Self { - let v = self.subst_vec(s); + fn substitute1(&self, s: &Substitution) -> Self { + let v = self.substitute(s); let [r] = v.try_into().unwrap(); // No row vars, so every Type produces exactly one r } @@ -458,10 +458,6 @@ impl Type { pub const fn new_row_var_use(idx: usize, bound: TypeBound) -> Self { Self(TypeEnum::RowVariable(idx, bound), bound) } - - fn substitute(&self, s: &Substitution) -> Vec { - self.subst_vec(s) - } } // ====== Conversions ====== diff --git a/hugr-core/src/types/type_param.rs b/hugr-core/src/types/type_param.rs index d81525d18..e1c03d695 100644 --- a/hugr-core/src/types/type_param.rs +++ b/hugr-core/src/types/type_param.rs @@ -284,7 +284,7 @@ impl TypeArg { match self { TypeArg::Type { ty } => { // RowVariables are represented as TypeArg::Variable - ty.substitute(t).into() + ty.substitute1(t).into() } TypeArg::BoundedNat { .. } => self.clone(), // We do not allow variables as bounds on BoundedNat's TypeArg::Opaque { diff --git a/hugr-core/src/types/type_row.rs b/hugr-core/src/types/type_row.rs index 268450f34..e76a2ce7f 100644 --- a/hugr-core/src/types/type_row.rs +++ b/hugr-core/src/types/type_row.rs @@ -66,7 +66,7 @@ impl TypeRow { /// For `TypeRow`, guaranteed not to change the length of the row. pub(super) fn substitute(&self, s: &Substitution) -> Self { self.iter() - .flat_map(|ty| ty.subst_vec(s)) + .flat_map(|ty| ty.substitute(s)) .collect::>() .into() } From 38ae4641422b794f0ad38e17e43f6b42723b11bc Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Fri, 31 May 2024 17:48:55 +0100 Subject: [PATCH 027/115] PolyFuncType::new avoids impl; add SignatureType from PFT and a bunch of annots --- hugr-core/src/extension/op_def.rs | 6 ++++++ hugr-core/src/extension/prelude.rs | 10 ++++++---- hugr-core/src/std_extensions/arithmetic/int_ops.rs | 6 +++--- hugr-core/src/std_extensions/collections.rs | 1 + hugr-core/src/types/poly_func.rs | 11 ++++++++++- 5 files changed, 26 insertions(+), 8 deletions(-) diff --git a/hugr-core/src/extension/op_def.rs b/hugr-core/src/extension/op_def.rs index 2ec90c7e7..c651c7d09 100644 --- a/hugr-core/src/extension/op_def.rs +++ b/hugr-core/src/extension/op_def.rs @@ -192,6 +192,12 @@ impl From for SignatureFunc { } } +impl From> for SignatureFunc { + fn from(v: PolyFuncType) -> Self { + Self::TypeScheme(CustomValidator::from_polyfunc(v)) + } +} + impl From for SignatureFunc { fn from(v: FunctionType) -> Self { Self::TypeScheme(CustomValidator::from_polyfunc(v)) diff --git a/hugr-core/src/extension/prelude.rs b/hugr-core/src/extension/prelude.rs index 9d701449b..463504002 100644 --- a/hugr-core/src/extension/prelude.rs +++ b/hugr-core/src/extension/prelude.rs @@ -27,8 +27,8 @@ impl SignatureFromArgs for ArrayOpCustom { }; let elem_ty_var = Type::new_var_use(0, TypeBound::Any); - let var_arg_row = vec![elem_ty_var.clone(); n as usize]; - let other_row = vec![array_type(TypeArg::BoundedNat { n }, elem_ty_var.clone())]; + let var_arg_row = vec![elem_ty_var.clone().into(); n as usize]; + let other_row = vec![array_type(TypeArg::BoundedNat { n }, elem_ty_var.clone()).into()]; Ok(PolyFuncType::new( vec![TypeBound::Any.into()], @@ -67,7 +67,7 @@ impl SignatureFromArgs for GenericOpCustom { }; outs.push(ty.clone()); } - Ok(PolyFuncType::new(vec![], FunctionType::new(inps, outs))) + Ok(PolyFuncType::new(vec![], FunctionType::new(inps, outs)).into()) } fn static_params(&self) -> &[TypeParam] { @@ -380,7 +380,9 @@ mod test { .instantiate([]) .unwrap(); - let ext_type = Type::new_extension(ext_def); + let ext_type = Type::::new_extension(ext_def); + assert_eq!(ext_type, ERROR_TYPE); + let ext_type = Type::::new_extension(ext_def); assert_eq!(ext_type, ERROR_TYPE); let error_val = ConstError::new(2, "my message"); diff --git a/hugr-core/src/std_extensions/arithmetic/int_ops.rs b/hugr-core/src/std_extensions/arithmetic/int_ops.rs index 546b2b6c3..2d9ec13dd 100644 --- a/hugr-core/src/std_extensions/arithmetic/int_ops.rs +++ b/hugr-core/src/std_extensions/arithmetic/int_ops.rs @@ -237,20 +237,20 @@ fn int_polytype( n_vars: usize, input: impl Into, output: impl Into, -) -> PolyFuncType { +) -> PolyFuncType { PolyFuncType::new( vec![LOG_WIDTH_TYPE_PARAM; n_vars], FunctionType::new(input, output), ) } -fn ibinop_sig() -> PolyFuncType { +fn ibinop_sig() -> PolyFuncType { let int_type_var = int_tv(0); int_polytype(1, vec![int_type_var.clone(); 2], vec![int_type_var]) } -fn iunop_sig() -> PolyFuncType { +fn iunop_sig() -> PolyFuncType { let int_type_var = int_tv(0); int_polytype(1, vec![int_type_var.clone()], vec![int_type_var]) } diff --git a/hugr-core/src/std_extensions/collections.rs b/hugr-core/src/std_extensions/collections.rs index 392417dff..f93f02110 100644 --- a/hugr-core/src/std_extensions/collections.rs +++ b/hugr-core/src/std_extensions/collections.rs @@ -151,6 +151,7 @@ fn extension() -> Extension { let list_type_def = extension.get_type(&LIST_TYPENAME).unwrap(); let (l, e) = list_and_elem_type_vars(list_type_def); + let (l, e): (Type, Type) = (l.into(), e.into()); extension .add_op( POP_NAME, diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index 22eaf09c9..5584c1bee 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -48,6 +48,15 @@ impl From> for PolyFuncType { } } +impl From> for PolyFuncType { + fn from(value: PolyFuncType) -> Self { + Self { + params: value.params, + body: value.body.into(), + } + } +} + impl TryFrom> for FunctionType { /// If the PolyFuncType is not monomorphic, fail with its binders type Error = Vec; @@ -74,7 +83,7 @@ impl PolyFuncType { /// Create a new PolyFuncType given the kinds of the variables it declares /// and the underlying function type. - pub fn new(params: impl Into>, body: impl Into>) -> Self { + pub fn new(params: impl Into>, body: FunctionType) -> Self { Self { params: params.into(), body: body.into(), From d25b1c6746bb16ba967228f9ba03cbcae8a8f6c9 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Fri, 31 May 2024 17:52:24 +0100 Subject: [PATCH 028/115] Revert "PolyFuncType::new avoids impl; add SignatureType from PFT and a bunch of annots" This reverts commit 38ae4641422b794f0ad38e17e43f6b42723b11bc. --- hugr-core/src/extension/op_def.rs | 6 ------ hugr-core/src/extension/prelude.rs | 10 ++++------ hugr-core/src/std_extensions/arithmetic/int_ops.rs | 6 +++--- hugr-core/src/std_extensions/collections.rs | 1 - hugr-core/src/types/poly_func.rs | 11 +---------- 5 files changed, 8 insertions(+), 26 deletions(-) diff --git a/hugr-core/src/extension/op_def.rs b/hugr-core/src/extension/op_def.rs index c651c7d09..2ec90c7e7 100644 --- a/hugr-core/src/extension/op_def.rs +++ b/hugr-core/src/extension/op_def.rs @@ -192,12 +192,6 @@ impl From for SignatureFunc { } } -impl From> for SignatureFunc { - fn from(v: PolyFuncType) -> Self { - Self::TypeScheme(CustomValidator::from_polyfunc(v)) - } -} - impl From for SignatureFunc { fn from(v: FunctionType) -> Self { Self::TypeScheme(CustomValidator::from_polyfunc(v)) diff --git a/hugr-core/src/extension/prelude.rs b/hugr-core/src/extension/prelude.rs index 463504002..9d701449b 100644 --- a/hugr-core/src/extension/prelude.rs +++ b/hugr-core/src/extension/prelude.rs @@ -27,8 +27,8 @@ impl SignatureFromArgs for ArrayOpCustom { }; let elem_ty_var = Type::new_var_use(0, TypeBound::Any); - let var_arg_row = vec![elem_ty_var.clone().into(); n as usize]; - let other_row = vec![array_type(TypeArg::BoundedNat { n }, elem_ty_var.clone()).into()]; + let var_arg_row = vec![elem_ty_var.clone(); n as usize]; + let other_row = vec![array_type(TypeArg::BoundedNat { n }, elem_ty_var.clone())]; Ok(PolyFuncType::new( vec![TypeBound::Any.into()], @@ -67,7 +67,7 @@ impl SignatureFromArgs for GenericOpCustom { }; outs.push(ty.clone()); } - Ok(PolyFuncType::new(vec![], FunctionType::new(inps, outs)).into()) + Ok(PolyFuncType::new(vec![], FunctionType::new(inps, outs))) } fn static_params(&self) -> &[TypeParam] { @@ -380,9 +380,7 @@ mod test { .instantiate([]) .unwrap(); - let ext_type = Type::::new_extension(ext_def); - assert_eq!(ext_type, ERROR_TYPE); - let ext_type = Type::::new_extension(ext_def); + let ext_type = Type::new_extension(ext_def); assert_eq!(ext_type, ERROR_TYPE); let error_val = ConstError::new(2, "my message"); diff --git a/hugr-core/src/std_extensions/arithmetic/int_ops.rs b/hugr-core/src/std_extensions/arithmetic/int_ops.rs index 2d9ec13dd..546b2b6c3 100644 --- a/hugr-core/src/std_extensions/arithmetic/int_ops.rs +++ b/hugr-core/src/std_extensions/arithmetic/int_ops.rs @@ -237,20 +237,20 @@ fn int_polytype( n_vars: usize, input: impl Into, output: impl Into, -) -> PolyFuncType { +) -> PolyFuncType { PolyFuncType::new( vec![LOG_WIDTH_TYPE_PARAM; n_vars], FunctionType::new(input, output), ) } -fn ibinop_sig() -> PolyFuncType { +fn ibinop_sig() -> PolyFuncType { let int_type_var = int_tv(0); int_polytype(1, vec![int_type_var.clone(); 2], vec![int_type_var]) } -fn iunop_sig() -> PolyFuncType { +fn iunop_sig() -> PolyFuncType { let int_type_var = int_tv(0); int_polytype(1, vec![int_type_var.clone()], vec![int_type_var]) } diff --git a/hugr-core/src/std_extensions/collections.rs b/hugr-core/src/std_extensions/collections.rs index f93f02110..392417dff 100644 --- a/hugr-core/src/std_extensions/collections.rs +++ b/hugr-core/src/std_extensions/collections.rs @@ -151,7 +151,6 @@ fn extension() -> Extension { let list_type_def = extension.get_type(&LIST_TYPENAME).unwrap(); let (l, e) = list_and_elem_type_vars(list_type_def); - let (l, e): (Type, Type) = (l.into(), e.into()); extension .add_op( POP_NAME, diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index 5584c1bee..22eaf09c9 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -48,15 +48,6 @@ impl From> for PolyFuncType { } } -impl From> for PolyFuncType { - fn from(value: PolyFuncType) -> Self { - Self { - params: value.params, - body: value.body.into(), - } - } -} - impl TryFrom> for FunctionType { /// If the PolyFuncType is not monomorphic, fail with its binders type Error = Vec; @@ -83,7 +74,7 @@ impl PolyFuncType { /// Create a new PolyFuncType given the kinds of the variables it declares /// and the underlying function type. - pub fn new(params: impl Into>, body: FunctionType) -> Self { + pub fn new(params: impl Into>, body: impl Into>) -> Self { Self { params: params.into(), body: body.into(), From 609785fcb59d36e38d9a7b974b342a03ebdf19f7 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Fri, 31 May 2024 18:00:59 +0100 Subject: [PATCH 029/115] Add PFT --into--> PFT, fix/undup declarative/signature.rs --- hugr-core/src/extension/declarative/signature.rs | 4 +--- hugr-core/src/types/poly_func.rs | 9 +++++++++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/hugr-core/src/extension/declarative/signature.rs b/hugr-core/src/extension/declarative/signature.rs index df1aaab3b..78b70ff68 100644 --- a/hugr-core/src/extension/declarative/signature.rs +++ b/hugr-core/src/extension/declarative/signature.rs @@ -57,9 +57,7 @@ impl SignatureDeclaration { }; let poly_func = PolyFuncType::new(op_params, body); - Ok(SignatureFunc::TypeScheme(CustomValidator::from_polyfunc( - poly_func, - ))) + Ok(poly_func.into()) } } diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index 22eaf09c9..2efb7ad1d 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -48,6 +48,15 @@ impl From> for PolyFuncType { } } +impl From> for PolyFuncType { + fn from(value: PolyFuncType) -> Self { + Self { + params: value.params, + body: value.body.into() + } + } +} + impl TryFrom> for FunctionType { /// If the PolyFuncType is not monomorphic, fail with its binders type Error = Vec; From c92350bc867e40399ce5fa197d2da73b2805c710 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sat, 1 Jun 2024 08:53:11 +0100 Subject: [PATCH 030/115] PFT from FT, PFT from FT, add FT.into_rv->true into_rv could be made more uniform --- hugr-core/src/types/poly_func.rs | 13 +++++++++++-- hugr-core/src/types/signature.rs | 8 ++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index 2efb7ad1d..895fafd29 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -39,11 +39,20 @@ pub struct PolyFuncType { body: FunctionType, } -impl From> for PolyFuncType { +impl From> for PolyFuncType { fn from(body: FunctionType) -> Self { Self { params: vec![], - body, + body: body.into_rv(), + } + } +} + +impl From> for PolyFuncType { + fn from(body: FunctionType) -> Self { + Self { + params: vec![], + body } } } diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index 0c160c458..f65c43599 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -94,6 +94,14 @@ impl FunctionType { self.output.validate(extension_registry, var_decls)?; self.extension_reqs.validate(var_decls) } + + pub(crate) fn into_rv(self) -> FunctionType { + FunctionType { + input: self.input.into_rv(), + output: self.output.into_rv(), + extension_reqs: self.extension_reqs + } + } } impl FunctionType { From 05c77802830471504b283106fb06ed3f0aa41f88 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sat, 1 Jun 2024 09:08:57 +0100 Subject: [PATCH 031/115] TypeArg from Type via try_into_no_rv --- hugr-core/src/types.rs | 6 +++--- hugr-core/src/types/type_param.rs | 11 +++++++---- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index 493c392b0..d6bc1f3f9 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -479,10 +479,10 @@ impl Type { } impl Type { - fn try_into_no_rv(self) -> Result, SignatureError> { - if let TypeEnum::RowVariable(idx, _) = self.0 { + fn try_into_no_rv(self) -> Result, (usize, TypeBound)> { + if let TypeEnum::RowVariable(idx, bound) = self.0 { assert!(RV); - return Err(SignatureError::RowVarWhereTypeExpected { idx }); + return Err((idx, bound)); } Ok(Type(self.0, self.1)) } diff --git a/hugr-core/src/types/type_param.rs b/hugr-core/src/types/type_param.rs index e1c03d695..7e1dfda59 100644 --- a/hugr-core/src/types/type_param.rs +++ b/hugr-core/src/types/type_param.rs @@ -183,9 +183,12 @@ pub enum TypeArg { }, } -impl From for TypeArg { - fn from(ty: Type) -> Self { - Self::Type { ty } +impl From> for TypeArg { + fn from(ty: Type) -> Self { + match ty.try_into_no_rv() { + Ok(ty) => Self::Type { ty }, + Err((idx, bound)) => TypeArg::new_var_use(idx, TypeParam::new_list(bound)) + } } } @@ -231,7 +234,7 @@ impl TypeArg { // Note a TypeParam::List of TypeParam::Type *cannot* be represented // as a TypeArg::Type because the latter stores a Type i.e. only a single type, // not a RowVariable. - TypeParam::Type { b } => Type::new_var_use(idx, b).into(), + TypeParam::Type { b } => Type::::new_var_use(idx, b).into(), // Prevent TypeArg::Variable(idx, TypeParam::Extensions) TypeParam::Extensions => TypeArg::Extensions { es: ExtensionSet::type_var(idx), From b2885fb7a65f3a54f72797a42fb284e189e980b2 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sat, 1 Jun 2024 09:16:16 +0100 Subject: [PATCH 032/115] fix builder/dataflow.rs - another call to make into_rv pub? --- hugr-core/src/builder/dataflow.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hugr-core/src/builder/dataflow.rs b/hugr-core/src/builder/dataflow.rs index ec9c087a7..cbde241df 100644 --- a/hugr-core/src/builder/dataflow.rs +++ b/hugr-core/src/builder/dataflow.rs @@ -218,7 +218,7 @@ pub(crate) mod test { use crate::std_extensions::logic::test::and_op; use crate::types::type_param::TypeParam; - use crate::types::{Type, TypeBound}; + use crate::types::{FunctionType, Type, TypeBound}; use crate::utils::test_quantum_extension::h_gate; use crate::{ builder::test::{n_identity, BIT, NAT, QB}, @@ -564,7 +564,7 @@ pub(crate) mod test { PolyFuncType::new( [TypeParam::new_list(TypeBound::Copyable)], FunctionType::new( - Type::new_function(FunctionType::new(USIZE_T, tv.clone())), + Type::new_function(FunctionType::new(Type::::from(USIZE_T), tv.clone())), vec![], ), ), From a65a4c02d35aeb4eeb178e52405255d0db112fb4 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sat, 1 Jun 2024 09:18:55 +0100 Subject: [PATCH 033/115] Missed/use import(s) --- hugr-core/src/builder/cfg.rs | 1 + hugr-core/src/ops/custom.rs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/hugr-core/src/builder/cfg.rs b/hugr-core/src/builder/cfg.rs index 847813abc..7704f95ef 100644 --- a/hugr-core/src/builder/cfg.rs +++ b/hugr-core/src/builder/cfg.rs @@ -402,6 +402,7 @@ pub(crate) mod test { use crate::hugr::validate::InterGraphEdgeError; use crate::hugr::ValidationError; + use crate::types::FunctionType; use crate::{builder::test::NAT, type_row}; use cool_asserts::assert_matches; diff --git a/hugr-core/src/ops/custom.rs b/hugr-core/src/ops/custom.rs index 47b64893f..cc49f147e 100644 --- a/hugr-core/src/ops/custom.rs +++ b/hugr-core/src/ops/custom.rs @@ -436,7 +436,7 @@ mod test { #[test] fn new_opaque_op() { - let sig = FunctionType::new_endo(vec![QB_T]); + let sig = Signature::new_endo(vec![QB_T]); let op: CustomOp = OpaqueOp::new( "res".try_into().unwrap(), "op", From 67167abbd4b26821e4507ba8449e0a8f79a50e88 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sat, 1 Jun 2024 09:21:50 +0100 Subject: [PATCH 034/115] Ooops, still had some try_new(_endo) --- hugr-core/src/extension/op_def.rs | 14 +++++++------- hugr-core/src/types/signature.rs | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/hugr-core/src/extension/op_def.rs b/hugr-core/src/extension/op_def.rs index 2ec90c7e7..4a9b3d1f0 100644 --- a/hugr-core/src/extension/op_def.rs +++ b/hugr-core/src/extension/op_def.rs @@ -611,7 +611,7 @@ pub(super) mod test { let list_usize = Type::new_extension(list_def.instantiate(vec![TypeArg::Type { ty: USIZE_T }])?); - let mut dfg = DFGBuilder::new(FunctionType::try_new_endo(vec![list_usize])?)?; + let mut dfg = DFGBuilder::new(FunctionType::new_endo(vec![list_usize]))?; let rev = dfg.add_dataflow_op( CustomOp::new_extension( e.instantiate_extension_op(&OP_NAME, vec![TypeArg::Type { ty: USIZE_T }], ®) @@ -663,10 +663,10 @@ pub(super) mod test { let args = [TypeArg::BoundedNat { n: 3 }, USIZE_T.into()]; assert_eq!( def.compute_signature(&args, &PRELUDE_REGISTRY), - Ok(FunctionType::try_new( + Ok(FunctionType::new( vec![USIZE_T; 3], vec![Type::new_tuple(vec![USIZE_T; 3])] - )?) + )) ); assert_eq!(def.validate_args(&args, &PRELUDE_REGISTRY, &[]), Ok(())); @@ -676,10 +676,10 @@ pub(super) mod test { let args = [TypeArg::BoundedNat { n: 3 }, tyvar.clone().into()]; assert_eq!( def.compute_signature(&args, &PRELUDE_REGISTRY), - Ok(FunctionType::try_new( + Ok(FunctionType::new( tyvars.clone(), vec![Type::new_tuple(tyvars)] - )?) + )) ); def.validate_args(&args, &PRELUDE_REGISTRY, &[TypeBound::Eq.into()]) .unwrap(); @@ -732,7 +732,7 @@ pub(super) mod test { def.validate_args(&args, &EMPTY_REG, &decls).unwrap(); assert_eq!( def.compute_signature(&args, &EMPTY_REG), - Ok(FunctionType::try_new_endo(tv)?) + Ok(FunctionType::new_endo(tv)) ); // But not with an external row variable let arg: TypeArg = Type::new_row_var_use(0, TypeBound::Eq).into(); @@ -766,7 +766,7 @@ pub(super) mod test { // Concrete extension set let es = ExtensionSet::singleton(&EXT_ID); - let exp_fun_ty = FunctionType::try_new_endo(BOOL_T)?.with_extension_delta(es.clone()); + let exp_fun_ty = FunctionType::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/types/signature.rs b/hugr-core/src/types/signature.rs index f65c43599..7bd42f1e9 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -276,7 +276,7 @@ mod test { use super::*; #[test] fn test_function_type() { - let mut f_type = FunctionType::try_new(Type::UNIT, Type::UNIT).unwrap(); + let mut f_type = FunctionType::new(Type::UNIT, Type::UNIT); assert_eq!(f_type.input_count(), 1); assert_eq!(f_type.output_count(), 1); From 21193fd75f0f5a4382676b587eee2e79534d2539 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sat, 1 Jun 2024 09:44:25 +0100 Subject: [PATCH 035/115] WIP serialize tests --- hugr-core/src/hugr/serialize/test.rs | 50 +++++++++++++++++++++++----- 1 file changed, 42 insertions(+), 8 deletions(-) diff --git a/hugr-core/src/hugr/serialize/test.rs b/hugr-core/src/hugr/serialize/test.rs index b386b3412..8a591c3d2 100644 --- a/hugr-core/src/hugr/serialize/test.rs +++ b/hugr-core/src/hugr/serialize/test.rs @@ -31,7 +31,7 @@ const QB: Type = crate::extension::prelude::QB_T; /// Version 1 of the Testing HUGR serialisation format, see `testing_hugr.py`. #[derive(Serialize, Deserialize, PartialEq, Debug, Default)] struct SerTestingV1 { - typ: Option, + typ: Option>, sum_type: Option, poly_func_type: Option, value: Option, @@ -86,13 +86,32 @@ macro_rules! impl_sertesting_from { }; } -impl_sertesting_from!(crate::types::Type, typ); +impl_sertesting_from!(crate::types::Type, typ); impl_sertesting_from!(crate::types::SumType, sum_type); impl_sertesting_from!(crate::types::PolyFuncType, poly_func_type); impl_sertesting_from!(crate::ops::Value, value); impl_sertesting_from!(NodeSer, optype); impl_sertesting_from!(SimpleOpDef, op_def); +#[cfg(test)] +impl From> for TestingModel { + fn from(v: PolyFuncType) -> Self { + let mut r: Self = Default::default(); + r.poly_func_type = Some(v.into()); + r + } +} + + +#[cfg(test)] +impl From> for TestingModel { + fn from(v: Type) -> Self { + let mut r: Self = Default::default(); + r.typ = Some(v.into()); + r + } +} + #[test] fn empty_hugr_serialize() { check_hugr_roundtrip(&Hugr::default(), true); @@ -366,12 +385,12 @@ fn constants_roundtrip() -> Result<(), Box> { #[test] fn serialize_types_roundtrip() { - let g: Type = Type::new_function(FunctionType::new_endo(vec![])); + let g: Type = Type::new_function(FunctionType::new_endo(vec![])); 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.into(), g]); check_testing_roundtrip(t); // A Classic sum @@ -407,14 +426,14 @@ fn roundtrip_sumtype(#[case] sum_type: SumType) { #[case(Value::true_val())] #[case(Value::unit_sum(3,5).unwrap())] #[case(Value::extension(ConstInt::new_u(2,1).unwrap()))] -#[case(Value::sum(1,[Value::extension(ConstInt::new_u(2,1).unwrap())], SumType::new([vec![], vec![INT_TYPES[2].clone()]])).unwrap())] +#[case(Value::sum(1,[Value::extension(ConstInt::new_u(2,1).unwrap())], SumType::new([vec![], vec![INT_TYPES[2].clone().into()]])).unwrap())] #[case(Value::tuple([Value::false_val(), Value::extension(ConstInt::new_s(2,1).unwrap())]))] #[case(Value::function(crate::builder::test::simple_dfg_hugr()).unwrap())] fn roundtrip_value(#[case] value: Value) { check_testing_roundtrip(value); } -fn polyfunctype1() -> PolyFuncType { +fn polyfunctype1() -> PolyFuncType { let mut extension_set = ExtensionSet::new(); extension_set.insert_type_var(1); let function_type = FunctionType::new_endo(type_row![]).with_extension_delta(extension_set); @@ -432,7 +451,7 @@ fn polyfunctype2() -> PolyFuncType { let res = PolyFuncType::new(params, FunctionType::new(inputs, tv1)); // Just check we've got the arguments the right way round // (not that it really matters for the serialization schema we have) - res.validate_var_len(&EMPTY_REG).unwrap(); + res.validate(&EMPTY_REG).unwrap(); res } @@ -447,7 +466,22 @@ fn polyfunctype2() -> PolyFuncType { [TypeParam::new_list(TypeBound::Any)], FunctionType::new_endo(Type::new_tuple(Type::new_row_var_use(0, TypeBound::Any)))))] #[case(polyfunctype2())] -fn roundtrip_polyfunctype(#[case] poly_func_type: PolyFuncType) { +fn roundtrip_polyfunctype_fixedlen(#[case] poly_func_type: PolyFuncType) { + check_testing_roundtrip(poly_func_type) +} + +#[rstest] +#[case(FunctionType::new_endo(type_row![]).into())] +#[case(polyfunctype1())] +#[case(PolyFuncType::new([TypeParam::Opaque { ty: int_custom_type(TypeArg::BoundedNat { n: 1 }) }], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Copyable)])))] +#[case(PolyFuncType::new([TypeBound::Eq.into()], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Eq)])))] +#[case(PolyFuncType::new([TypeParam::new_list(TypeBound::Any)], FunctionType::new_endo(type_row![])))] +#[case(PolyFuncType::new([TypeParam::Tuple { params: [TypeBound::Any.into(), TypeParam::bounded_nat(2.try_into().unwrap())].into() }], FunctionType::new_endo(type_row![])))] +#[case(PolyFuncType::new( + [TypeParam::new_list(TypeBound::Any)], + FunctionType::new_endo(Type::new_row_var_use(0, TypeBound::Any))))] +#[case(polyfunctype2())] +fn roundtrip_polyfunctype_varlen(#[case] poly_func_type: PolyFuncType) { check_testing_roundtrip(poly_func_type) } From 161056407136b1f6b50bbf6bd3897869d0045030 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sat, 1 Jun 2024 15:29:29 +0100 Subject: [PATCH 036/115] Combine conversions as into_ using generic static asserts --- hugr-core/src/std_extensions/logic.rs | 2 +- hugr-core/src/types.rs | 20 +++++++++++--------- hugr-core/src/types/poly_func.rs | 18 +++++------------- hugr-core/src/types/signature.rs | 11 ++++++----- hugr-core/src/types/type_row.rs | 7 ++++--- hugr-passes/src/const_fold.rs | 2 +- 6 files changed, 28 insertions(+), 32 deletions(-) diff --git a/hugr-core/src/std_extensions/logic.rs b/hugr-core/src/std_extensions/logic.rs index 7f62b129b..475b5460c 100644 --- a/hugr-core/src/std_extensions/logic.rs +++ b/hugr-core/src/std_extensions/logic.rs @@ -163,7 +163,7 @@ fn logic_op_sig() -> impl SignatureFromArgs { return Err(SignatureError::InvalidTypeArgs); }; let var_arg_row = TypeRow::from(vec![BOOL_T; n as usize]); - Ok(FunctionType::new(var_arg_row.into_rv(), vec![BOOL_T.into()]).into()) + Ok(FunctionType::new(var_arg_row, vec![BOOL_T.into_()]).into()) } fn static_params(&self) -> &[TypeParam] { diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index d6bc1f3f9..e084a9277 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -8,6 +8,8 @@ mod signature; pub mod type_param; pub mod type_row; +use std::marker::PhantomData; + pub use crate::ops::constant::{ConstTypeError, CustomCheckFailure}; use crate::types::type_param::check_type_arg; use crate::utils::display_list_with_separator; @@ -248,6 +250,11 @@ impl TypeEnum { } } +struct Implies(PhantomData>, PhantomData>); +impl Implies { + const A_IMPLIES_B: () = assert!(B || !A); +} + #[derive(Clone, Debug, Eq, derive_more::Display, serde::Serialize, serde::Deserialize)] #[display(fmt = "{}", "_0")] #[serde( @@ -311,7 +318,7 @@ impl Type { { let variants: Vec>> = variants .into_iter() - .map(|t| t.into_owned().into_iter().map(Type::into_rv).collect()) + .map(|t| t.into_owned().into_iter().map(Type::into_).collect()) .collect(); Self::new(TypeEnum::Sum(SumType::new(variants))) } @@ -461,12 +468,6 @@ impl Type { } // ====== Conversions ====== -impl Type { - fn into_(self) -> Type { - Type(self.0, self.1) - } -} - impl Type { fn try_into_(self) -> Result, SignatureError> { if !RV { @@ -487,14 +488,15 @@ impl Type { Ok(Type(self.0, self.1)) } - fn into_rv(self) -> Type { + pub fn into_(self) -> Type { + let _ = Implies::::A_IMPLIES_B; Type(self.0, self.1) } } impl From> for Type { fn from(value: Type) -> Self { - value.into_() // .into_rv also fine + value.into_() } } diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index 895fafd29..f4934ff3f 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -9,7 +9,7 @@ use { proptest_derive::Arbitrary, }; -use super::signature::FunctionType; +use super::{signature::FunctionType, Implies}; use super::type_param::{check_type_args, TypeArg, TypeParam}; use super::Substitution; @@ -39,20 +39,12 @@ pub struct PolyFuncType { body: FunctionType, } -impl From> for PolyFuncType { - fn from(body: FunctionType) -> Self { +impl From> for PolyFuncType { + fn from(body: FunctionType) -> Self { + let _ = Implies::::A_IMPLIES_B; Self { params: vec![], - body: body.into_rv(), - } - } -} - -impl From> for PolyFuncType { - fn from(body: FunctionType) -> Self { - Self { - params: vec![], - body + body: body.into_(), } } } diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index 7bd42f1e9..89d74715e 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -5,7 +5,7 @@ use itertools::Either; use std::fmt::{self, Display, Write}; use super::type_param::TypeParam; -use super::{Substitution, Type, TypeBound, TypeEnum, TypeRow}; +use super::{Implies, Substitution, Type, TypeBound, TypeEnum, TypeRow}; use crate::core::PortIndex; use crate::extension::{ExtensionRegistry, ExtensionSet, SignatureError}; @@ -95,10 +95,11 @@ impl FunctionType { self.extension_reqs.validate(var_decls) } - pub(crate) fn into_rv(self) -> FunctionType { + pub(crate) fn into_(self) -> FunctionType { + let _ = Implies::::A_IMPLIES_B; FunctionType { - input: self.input.into_rv(), - output: self.output.into_rv(), + input: self.input.into_(), + output: self.output.into_(), extension_reqs: self.extension_reqs } } @@ -256,7 +257,7 @@ impl TryFrom for Signature { impl From for FunctionType { fn from(value: Signature) -> Self { - Self::new(value.input.into_rv(), value.output.into_rv()) + Self::new(value.input.into_(), value.output.into_()) .with_extension_delta(value.extension_reqs) } } diff --git a/hugr-core/src/types/type_row.rs b/hugr-core/src/types/type_row.rs index e76a2ce7f..cc278253d 100644 --- a/hugr-core/src/types/type_row.rs +++ b/hugr-core/src/types/type_row.rs @@ -7,7 +7,7 @@ use std::{ ops::{Deref, DerefMut}, }; -use super::{type_param::TypeParam, Substitution, Type}; +use super::{type_param::TypeParam, Implies, Substitution, Type}; use crate::{ extension::{ExtensionRegistry, SignatureError}, utils::display_list, @@ -95,12 +95,13 @@ impl TypeRow { self.iter().try_for_each(|t| t.validate(exts, var_decls)) } - pub fn into_rv(self) -> TypeRow { + pub fn into_(self) -> TypeRow { + let _ = Implies::::A_IMPLIES_B; TypeRow::from( self.types .iter() .cloned() - .map(Type::into_rv) + .map(Type::into_) .collect::>(), ) } diff --git a/hugr-passes/src/const_fold.rs b/hugr-passes/src/const_fold.rs index 82a3dd83e..00986806e 100644 --- a/hugr-passes/src/const_fold.rs +++ b/hugr-passes/src/const_fold.rs @@ -64,7 +64,7 @@ pub fn fold_leaf_op(op: &OpType, consts: &[(IncomingPort, Value)]) -> ConstFoldR OpType::Tag(t) => out_row([Value::sum( t.tag, consts.iter().map(|(_, konst)| konst.clone()), - SumType::new(t.variants.iter().cloned().map(TypeRow::into_rv)), + SumType::new(t.variants.iter().cloned().map(TypeRow::into_)), ) .unwrap()]), OpType::CustomOp(op) => { From 2d2815cbac9f6537300d43e41068fa70b41a5bd0 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sat, 1 Jun 2024 15:40:06 +0100 Subject: [PATCH 037/115] Simplify logic.rs (no change to errors) --- hugr-core/src/std_extensions/logic.rs | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/hugr-core/src/std_extensions/logic.rs b/hugr-core/src/std_extensions/logic.rs index 475b5460c..434fee5f7 100644 --- a/hugr-core/src/std_extensions/logic.rs +++ b/hugr-core/src/std_extensions/logic.rs @@ -5,7 +5,7 @@ use strum_macros::{EnumIter, EnumString, IntoStaticStr}; use crate::extension::{ConstFold, ConstFoldResult}; use crate::ops::constant::ValueName; use crate::ops::{OpName, Value}; -use crate::types::TypeRow; +use crate::types::FunctionType; use crate::{ extension::{ prelude::BOOL_T, @@ -14,10 +14,7 @@ use crate::{ }, ops::{self, custom::ExtensionOp, NamedOp}, type_row, - types::{ - type_param::{TypeArg, TypeParam}, - FunctionType, - }, + types::type_param::{TypeArg, TypeParam}, utils::sorted_consts, Extension, IncomingPort, }; @@ -162,7 +159,7 @@ fn logic_op_sig() -> impl SignatureFromArgs { let [TypeArg::BoundedNat { n }] = *arg_values else { return Err(SignatureError::InvalidTypeArgs); }; - let var_arg_row = TypeRow::from(vec![BOOL_T; n as usize]); + let var_arg_row = vec![BOOL_T; n as usize]; Ok(FunctionType::new(var_arg_row, vec![BOOL_T.into_()]).into()) } From 28ed814d026f54dea9ce3db3dc9e5ddf82c3cac0 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sat, 1 Jun 2024 15:45:49 +0100 Subject: [PATCH 038/115] Combine SignatureFunc Into's using into_ (no change to errors) --- hugr-core/src/extension/op_def.rs | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/hugr-core/src/extension/op_def.rs b/hugr-core/src/extension/op_def.rs index 4a9b3d1f0..88c618543 100644 --- a/hugr-core/src/extension/op_def.rs +++ b/hugr-core/src/extension/op_def.rs @@ -192,19 +192,12 @@ impl From for SignatureFunc { } } -impl From for SignatureFunc { - fn from(v: FunctionType) -> Self { +impl From> for SignatureFunc { + fn from(v: FunctionType) -> Self { Self::TypeScheme(CustomValidator::from_polyfunc(v)) } } -impl From for SignatureFunc { - fn from(value: Signature) -> Self { - let value: FunctionType = value.into(); - Self::TypeScheme(CustomValidator::from_polyfunc(value)) - } -} - impl From for SignatureFunc { fn from(v: CustomValidator) -> Self { Self::TypeScheme(v) From 0cdee9780aff0e58e7b5ef837f3bcbb985a564a6 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sat, 1 Jun 2024 15:47:46 +0100 Subject: [PATCH 039/115] More flex in TypeRow::from (too much - errors in "cargo build" nvm "cargo test") --- hugr-core/src/types/type_row.rs | 37 +++++++++++++++++++++++---------- 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/hugr-core/src/types/type_row.rs b/hugr-core/src/types/type_row.rs index cc278253d..480c49d2c 100644 --- a/hugr-core/src/types/type_row.rs +++ b/hugr-core/src/types/type_row.rs @@ -126,11 +126,11 @@ impl TypeRow { } } -/*impl From for TypeRow { +impl From for TypeRow { fn from(value: TypeRow) -> Self { Self::from(value.into_owned().into_iter().map_into().collect::>>()) } -}*/ +} /*impl Into]>> for TypeRow { fn into(self) -> Cow<'static, [Type]> { @@ -159,21 +159,36 @@ impl Default for TypeRow { } } -impl From for TypeRow -where - F: Into]>>, -{ - fn from(types: F) -> Self { +impl From>> for TypeRow { + fn from(types: Vec>) -> Self { + Self { + types: types.into() + } + } +} + +impl From> for TypeRow { + fn from(types: Vec) -> Self { + Self { + types: types.into_iter().map(Type::into_).collect() + } + } +} + + +impl From<&'static [Type]> for TypeRow { + fn from(types: &'static [Type]) -> Self { Self { - types: types.into(), + types: types.into() } } } -impl From> for TypeRow { - fn from(t: Type) -> Self { +impl From> for TypeRow { + fn from(t: Type) -> Self { + let _ = Implies::::A_IMPLIES_B; Self { - types: vec![t].into(), + types: vec![t.into_()].into(), } } } From 57407e11ca447ca5420242fb7cd172e829a66a5d Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sat, 1 Jun 2024 17:27:12 +0100 Subject: [PATCH 040/115] PFT::new and FT -> SigFunc don't convert. Build the correct FunctionType. FT -> PFT does...hope return type typically known --- hugr-core/src/extension/op_def.rs | 4 ++-- hugr-core/src/types/poly_func.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/hugr-core/src/extension/op_def.rs b/hugr-core/src/extension/op_def.rs index 88c618543..5967d70d2 100644 --- a/hugr-core/src/extension/op_def.rs +++ b/hugr-core/src/extension/op_def.rs @@ -192,8 +192,8 @@ impl From for SignatureFunc { } } -impl From> for SignatureFunc { - fn from(v: FunctionType) -> Self { +impl From for SignatureFunc { + fn from(v: FunctionType) -> Self { Self::TypeScheme(CustomValidator::from_polyfunc(v)) } } diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index f4934ff3f..40983327f 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -84,10 +84,10 @@ impl PolyFuncType { /// Create a new PolyFuncType given the kinds of the variables it declares /// and the underlying function type. - pub fn new(params: impl Into>, body: impl Into>) -> Self { + pub fn new(params: impl Into>, body: FunctionType) -> Self { Self { params: params.into(), - body: body.into(), + body } } From 1c81a2bcb80ca454738f3afc1854ff42c03c4c69 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sat, 1 Jun 2024 17:54:55 +0100 Subject: [PATCH 041/115] Various build fixes - only new_tuple / Sum remain --- .../src/extension/declarative/signature.rs | 2 +- hugr-core/src/extension/prelude.rs | 2 +- .../std_extensions/arithmetic/conversions.rs | 19 ++++++++----------- .../src/std_extensions/arithmetic/int_ops.rs | 12 ++++++------ hugr-core/src/std_extensions/logic.rs | 2 +- hugr-core/src/types/signature.rs | 2 +- hugr-passes/src/const_fold.rs | 2 +- 7 files changed, 19 insertions(+), 22 deletions(-) diff --git a/hugr-core/src/extension/declarative/signature.rs b/hugr-core/src/extension/declarative/signature.rs index 78b70ff68..f8482b6b4 100644 --- a/hugr-core/src/extension/declarative/signature.rs +++ b/hugr-core/src/extension/declarative/signature.rs @@ -41,7 +41,7 @@ impl SignatureDeclaration { op_params: &[TypeParam], ) -> Result { let make_type_row = - |v: &[SignaturePortDeclaration]| -> Result { + |v: &[SignaturePortDeclaration]| -> Result, ExtensionDeclarationError> { let types = v .iter() .map(|port_decl| port_decl.make_types(ext, ctx, op_params)) diff --git a/hugr-core/src/extension/prelude.rs b/hugr-core/src/extension/prelude.rs index 9d701449b..932bcda58 100644 --- a/hugr-core/src/extension/prelude.rs +++ b/hugr-core/src/extension/prelude.rs @@ -268,7 +268,7 @@ pub const ERROR_TYPE_NAME: TypeName = TypeName::new_inline("error"); /// Return a Sum type with the first variant as the given type and the second an Error. pub fn sum_with_error(ty: Type) -> SumType { - SumType::new([vec![ty.into()], vec![ERROR_TYPE.into()]]) + SumType::new([ty, ERROR_TYPE]) } #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] diff --git a/hugr-core/src/std_extensions/arithmetic/conversions.rs b/hugr-core/src/std_extensions/arithmetic/conversions.rs index b6dcab87b..b19d7897f 100644 --- a/hugr-core/src/std_extensions/arithmetic/conversions.rs +++ b/hugr-core/src/std_extensions/arithmetic/conversions.rs @@ -3,6 +3,7 @@ use strum_macros::{EnumIter, EnumString, IntoStaticStr}; use crate::ops::OpName; +use crate::types::Type; use crate::{ extension::{ prelude::sum_with_error, @@ -41,21 +42,17 @@ impl MakeOpDef for ConvertOpDef { fn signature(&self) -> SignatureFunc { use ConvertOpDef::*; + PolyFuncType::new( + vec![LOG_WIDTH_TYPE_PARAM], match self { - trunc_s | trunc_u => PolyFuncType::new( - vec![LOG_WIDTH_TYPE_PARAM], + trunc_s | trunc_u => FunctionType::new( type_row![FLOAT64_TYPE], - vec![sum_with_error(int_tv(0)).into()], + Type::::from(sum_with_error(int_tv(0))) ), - ), - - convert_s | convert_u => PolyFuncType::new( - vec![LOG_WIDTH_TYPE_PARAM], - FunctionType::new(vec![int_tv(0)], type_row![FLOAT64_TYPE]), - ), - } - .into() + convert_s | convert_u => + FunctionType::new(vec![int_tv(0)], type_row![FLOAT64_TYPE]) + }).into() } fn description(&self) -> String { diff --git a/hugr-core/src/std_extensions/arithmetic/int_ops.rs b/hugr-core/src/std_extensions/arithmetic/int_ops.rs index 546b2b6c3..ff563c0ac 100644 --- a/hugr-core/src/std_extensions/arithmetic/int_ops.rs +++ b/hugr-core/src/std_extensions/arithmetic/int_ops.rs @@ -112,7 +112,7 @@ impl MakeOpDef for IntOpDef { ) .into(), inarrow_s | inarrow_u => CustomValidator::new_with_validator( - int_polytype(2, vec![int_tv(0)], vec![sum_with_error(int_tv(1)).into()]), + int_polytype(2, int_tv(0), sum_with_error(int_tv(1)).into()), IOValidator { f_ge_s: true }, ) .into(), @@ -131,7 +131,7 @@ impl MakeOpDef for IntOpDef { int_polytype( 2, intpair.clone(), - vec![sum_with_error(Type::new_tuple(intpair)).into()], + sum_with_error(Type::new_tuple(intpair)).into(), ) } .into(), @@ -144,13 +144,13 @@ impl MakeOpDef for IntOpDef { idiv_checked_u | idiv_checked_s => int_polytype( 2, vec![int_tv(0), int_tv(1)], - vec![sum_with_error(int_tv(0)).into()], + sum_with_error(int_tv(0)).into(), ) .into(), imod_checked_u | imod_checked_s => int_polytype( 2, vec![int_tv(0), int_tv(1).clone()], - vec![sum_with_error(int_tv(1)).into()], + sum_with_error(int_tv(1)).into(), ) .into(), imod_u | imod_s => { @@ -235,8 +235,8 @@ impl MakeOpDef for IntOpDef { } fn int_polytype( n_vars: usize, - input: impl Into, - output: impl Into, + input: impl Into>, + output: impl Into>, ) -> PolyFuncType { PolyFuncType::new( vec![LOG_WIDTH_TYPE_PARAM; n_vars], diff --git a/hugr-core/src/std_extensions/logic.rs b/hugr-core/src/std_extensions/logic.rs index 434fee5f7..995db6702 100644 --- a/hugr-core/src/std_extensions/logic.rs +++ b/hugr-core/src/std_extensions/logic.rs @@ -160,7 +160,7 @@ fn logic_op_sig() -> impl SignatureFromArgs { return Err(SignatureError::InvalidTypeArgs); }; let var_arg_row = vec![BOOL_T; n as usize]; - Ok(FunctionType::new(var_arg_row, vec![BOOL_T.into_()]).into()) + Ok(FunctionType::::new(var_arg_row, vec![BOOL_T]).into()) } fn static_params(&self) -> &[TypeParam] { diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index 89d74715e..6b926f3d4 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -257,7 +257,7 @@ impl TryFrom for Signature { impl From for FunctionType { fn from(value: Signature) -> Self { - Self::new(value.input.into_(), value.output.into_()) + Self::new(value.input, value.output) .with_extension_delta(value.extension_reqs) } } diff --git a/hugr-passes/src/const_fold.rs b/hugr-passes/src/const_fold.rs index 00986806e..ba52685f2 100644 --- a/hugr-passes/src/const_fold.rs +++ b/hugr-passes/src/const_fold.rs @@ -64,7 +64,7 @@ pub fn fold_leaf_op(op: &OpType, consts: &[(IncomingPort, Value)]) -> ConstFoldR OpType::Tag(t) => out_row([Value::sum( t.tag, consts.iter().map(|(_, konst)| konst.clone()), - SumType::new(t.variants.iter().cloned().map(TypeRow::into_)), + SumType::new(t.variants.clone()), ) .unwrap()]), OpType::CustomOp(op) => { From 4d59b0cbab83758cc73fd5bfd5ecc1d7b5581ca7 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sat, 1 Jun 2024 18:08:04 +0100 Subject: [PATCH 042/115] new_tuple takes only into-TypeRow --- hugr-core/src/types.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index e084a9277..df3191485 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -304,7 +304,7 @@ impl Type { /// Initialize a new tuple type by providing the elements. #[inline(always)] - pub fn new_tuple(types: impl Into>) -> Self { + pub fn new_tuple(types: impl Into>) -> Self { let row = types.into(); match row.len() { 0 => Self::UNIT, From 736938fe54e0f18e9c920889044dbbfd8d086b7e Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Sat, 1 Jun 2024 18:22:29 +0100 Subject: [PATCH 043/115] int_ops.rs: add sum_ty_with_err --- .../src/std_extensions/arithmetic/int_ops.rs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/hugr-core/src/std_extensions/arithmetic/int_ops.rs b/hugr-core/src/std_extensions/arithmetic/int_ops.rs index ff563c0ac..a7c3def8e 100644 --- a/hugr-core/src/std_extensions/arithmetic/int_ops.rs +++ b/hugr-core/src/std_extensions/arithmetic/int_ops.rs @@ -112,7 +112,7 @@ impl MakeOpDef for IntOpDef { ) .into(), inarrow_s | inarrow_u => CustomValidator::new_with_validator( - int_polytype(2, int_tv(0), sum_with_error(int_tv(1)).into()), + int_polytype(2, int_tv(0), sum_ty_with_err(int_tv(1))), IOValidator { f_ge_s: true }, ) .into(), @@ -131,7 +131,7 @@ impl MakeOpDef for IntOpDef { int_polytype( 2, intpair.clone(), - sum_with_error(Type::new_tuple(intpair)).into(), + sum_ty_with_err(Type::new_tuple(intpair)), ) } .into(), @@ -144,13 +144,13 @@ impl MakeOpDef for IntOpDef { idiv_checked_u | idiv_checked_s => int_polytype( 2, vec![int_tv(0), int_tv(1)], - sum_with_error(int_tv(0)).into(), + sum_ty_with_err(int_tv(0)), ) .into(), imod_checked_u | imod_checked_s => int_polytype( 2, vec![int_tv(0), int_tv(1).clone()], - sum_with_error(int_tv(1)).into(), + sum_ty_with_err(int_tv(1)), ) .into(), imod_u | imod_s => { @@ -347,6 +347,10 @@ impl IntOpDef { } } +fn sum_ty_with_err(t: Type) -> Type { + sum_with_error(t).into() +} + #[cfg(test)] mod test { use crate::{ops::dataflow::DataflowOpTrait, std_extensions::arithmetic::int_types::int_type}; @@ -387,7 +391,7 @@ mod test { .to_extension_op() .unwrap() .signature(), - FunctionType::new(vec![int_type(3)], vec![sum_with_error(int_type(3)).into()],) + FunctionType::new(vec![int_type(3)], vec![sum_ty_with_err(int_type(3))],) ); assert!( IntOpDef::iwiden_u @@ -403,7 +407,7 @@ mod test { .to_extension_op() .unwrap() .signature(), - FunctionType::new(vec![int_type(2)], vec![sum_with_error(int_type(1)).into()],) + FunctionType::new(vec![int_type(2)], vec![sum_ty_with_err(int_type(1))],) ); assert!(IntOpDef::inarrow_u From 3939776d3031fa22b1dc1f26f5a85f1c35f0c83c Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Mon, 10 Jun 2024 16:39:10 +0100 Subject: [PATCH 044/115] No TypeRow --Into-> TypeRow - too many type-annots-reqd problems --- hugr-core/src/types/type_row.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hugr-core/src/types/type_row.rs b/hugr-core/src/types/type_row.rs index 480c49d2c..1d055590c 100644 --- a/hugr-core/src/types/type_row.rs +++ b/hugr-core/src/types/type_row.rs @@ -126,11 +126,11 @@ impl TypeRow { } } -impl From for TypeRow { +/*impl From for TypeRow { fn from(value: TypeRow) -> Self { Self::from(value.into_owned().into_iter().map_into().collect::>>()) } -} +}*/ /*impl Into]>> for TypeRow { fn into(self) -> Cow<'static, [Type]> { From 372496598ff7712d0cd1cd7988e0febedf5718b1 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Mon, 10 Jun 2024 17:06:11 +0100 Subject: [PATCH 045/115] Reduce error count to zero and a bunch new ones show up in new places --- hugr-core/src/extension/op_def.rs | 6 ++++++ hugr-core/src/ops/leaf.rs | 4 ++-- hugr-core/src/std_extensions/arithmetic/conversions.rs | 4 ++-- hugr-core/src/std_extensions/arithmetic/int_ops.rs | 10 +++++----- hugr-core/src/types/signature.rs | 8 ++++---- hugr-passes/src/const_fold.rs | 2 +- hugr-passes/src/const_fold/test.rs | 4 ++-- hugr-passes/src/merge_bbs.rs | 2 +- 8 files changed, 23 insertions(+), 17 deletions(-) diff --git a/hugr-core/src/extension/op_def.rs b/hugr-core/src/extension/op_def.rs index 5967d70d2..c8fad2c47 100644 --- a/hugr-core/src/extension/op_def.rs +++ b/hugr-core/src/extension/op_def.rs @@ -198,6 +198,12 @@ impl From for SignatureFunc { } } +impl From for SignatureFunc { + fn from(v: Signature) -> Self { + Self::TypeScheme(CustomValidator::from_polyfunc(FunctionType::::from(v))) + } +} + impl From for SignatureFunc { fn from(v: CustomValidator) -> Self { Self::TypeScheme(v) diff --git a/hugr-core/src/ops/leaf.rs b/hugr-core/src/ops/leaf.rs index 5b4cebe59..d2f43823a 100644 --- a/hugr-core/src/ops/leaf.rs +++ b/hugr-core/src/ops/leaf.rs @@ -145,7 +145,7 @@ impl DataflowOpTrait for MakeTuple { /// The signature of the operation. fn signature(&self) -> Signature { - FunctionType::new(self.tys.clone(), vec![Type::new_tuple(self.tys.clone())]) + FunctionType::new(self.tys.clone(), vec![Type::new_tuple(self.tys.clone().into_())]) } fn other_input(&self) -> Option { @@ -167,7 +167,7 @@ impl DataflowOpTrait for UnpackTuple { /// The signature of the operation. fn signature(&self) -> Signature { - FunctionType::new(vec![Type::new_tuple(self.tys.clone())], self.tys.clone()) + FunctionType::new(vec![Type::new_tuple(self.tys.clone().into_())], self.tys.clone()) } fn other_input(&self) -> Option { diff --git a/hugr-core/src/std_extensions/arithmetic/conversions.rs b/hugr-core/src/std_extensions/arithmetic/conversions.rs index b19d7897f..5fd1c0392 100644 --- a/hugr-core/src/std_extensions/arithmetic/conversions.rs +++ b/hugr-core/src/std_extensions/arithmetic/conversions.rs @@ -47,11 +47,11 @@ impl MakeOpDef for ConvertOpDef { match self { trunc_s | trunc_u => FunctionType::new( - type_row![FLOAT64_TYPE], + type_row![FLOAT64_TYPE].into_(), Type::::from(sum_with_error(int_tv(0))) ), convert_s | convert_u => - FunctionType::new(vec![int_tv(0)], type_row![FLOAT64_TYPE]) + FunctionType::new(vec![int_tv(0)], type_row![FLOAT64_TYPE].into_()) }).into() } diff --git a/hugr-core/src/std_extensions/arithmetic/int_ops.rs b/hugr-core/src/std_extensions/arithmetic/int_ops.rs index a7c3def8e..07730a7b8 100644 --- a/hugr-core/src/std_extensions/arithmetic/int_ops.rs +++ b/hugr-core/src/std_extensions/arithmetic/int_ops.rs @@ -116,10 +116,10 @@ impl MakeOpDef for IntOpDef { IOValidator { f_ge_s: true }, ) .into(), - itobool => int_polytype(0, vec![int_type(0)], type_row![BOOL_T]).into(), - ifrombool => int_polytype(0, type_row![BOOL_T], vec![int_type(0)]).into(), + itobool => int_polytype(0, vec![int_type(0)], type_row![BOOL_T].into_()).into(), + ifrombool => int_polytype(0, type_row![BOOL_T].into_(), vec![int_type(0)]).into(), ieq | ine | ilt_u | ilt_s | igt_u | igt_s | ile_u | ile_s | ige_u | ige_s => { - int_polytype(1, vec![int_tv(0); 2], type_row![BOOL_T]).into() + int_polytype(1, vec![int_tv(0); 2], type_row![BOOL_T].into_()).into() } imax_u | imax_s | imin_u | imin_s | iadd | isub | imul | iand | ior | ixor => { ibinop_sig().into() @@ -127,7 +127,7 @@ impl MakeOpDef for IntOpDef { ineg | iabs | inot => iunop_sig().into(), //TODO inline idivmod_checked_u | idivmod_checked_s => { - let intpair: TypeRow = vec![int_tv(0), int_tv(1)].into(); + let intpair: TypeRow = vec![int_tv(0), int_tv(1)].into(); int_polytype( 2, intpair.clone(), @@ -136,7 +136,7 @@ impl MakeOpDef for IntOpDef { } .into(), idivmod_u | idivmod_s => { - let intpair: TypeRow = vec![int_tv(0), int_tv(1)].into(); + let intpair: TypeRow = vec![int_tv(0), int_tv(1)].into(); int_polytype(2, intpair.clone(), intpair.clone()) } .into(), diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index 6b926f3d4..18adc7827 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -257,7 +257,7 @@ impl TryFrom for Signature { impl From for FunctionType { fn from(value: Signature) -> Self { - Self::new(value.input, value.output) + Self::new(value.input.into_(), value.output.into_()) .with_extension_delta(value.extension_reqs) } } @@ -277,11 +277,11 @@ mod test { use super::*; #[test] fn test_function_type() { - let mut f_type = FunctionType::new(Type::UNIT, Type::UNIT); + let mut f_type = FunctionType::new(Type::::UNIT, Type::::UNIT); assert_eq!(f_type.input_count(), 1); assert_eq!(f_type.output_count(), 1); - assert_eq!(f_type.input_types(), &[Type::UNIT]); + assert_eq!(f_type.input_types(), &[Type::::UNIT]); assert_eq!( f_type.port_type(Port::new(Direction::Incoming, 0)), @@ -293,7 +293,7 @@ mod test { assert_eq!(f_type.port_type(out), Some(&USIZE_T)); - assert_eq!(f_type.input_types(), &[Type::UNIT]); + assert_eq!(f_type.input_types(), &[Type::::UNIT]); assert_eq!(f_type.output_types(), &[USIZE_T]); } } diff --git a/hugr-passes/src/const_fold.rs b/hugr-passes/src/const_fold.rs index ba52685f2..9f496de32 100644 --- a/hugr-passes/src/const_fold.rs +++ b/hugr-passes/src/const_fold.rs @@ -64,7 +64,7 @@ pub fn fold_leaf_op(op: &OpType, consts: &[(IncomingPort, Value)]) -> ConstFoldR OpType::Tag(t) => out_row([Value::sum( t.tag, consts.iter().map(|(_, konst)| konst.clone()), - SumType::new(t.variants.clone()), + SumType::new(t.variants.clone().into_iter().map(TypeRow::into_)), ) .unwrap()]), OpType::CustomOp(op) => { diff --git a/hugr-passes/src/const_fold/test.rs b/hugr-passes/src/const_fold/test.rs index 3f5eb2ba4..4ba292f7c 100644 --- a/hugr-passes/src/const_fold/test.rs +++ b/hugr-passes/src/const_fold/test.rs @@ -919,7 +919,7 @@ fn test_fold_idivmod_checked_u() { // x0, x1 := int_u<5>(20), int_u<3>(0) // x2 := idivmod_checked_u(x0, x1) // output x2 == error - let intpair: TypeRow = vec![INT_TYPES[5].clone(), INT_TYPES[3].clone()].into(); + let intpair: TypeRow = vec![INT_TYPES[5].clone(), INT_TYPES[3].clone()].into(); let sum_type = sum_with_error(Type::new_tuple(intpair)); let mut build = DFGBuilder::new(FunctionType::new( type_row![], @@ -994,7 +994,7 @@ fn test_fold_idivmod_checked_s() { // x0, x1 := int_s<5>(-20), int_u<3>(0) // x2 := idivmod_checked_s(x0, x1) // output x2 == error - let intpair: TypeRow = vec![INT_TYPES[5].clone(), INT_TYPES[3].clone()].into(); + let intpair: TypeRow = vec![INT_TYPES[5].clone(), INT_TYPES[3].clone()].into(); let sum_type = sum_with_error(Type::new_tuple(intpair)); let mut build = DFGBuilder::new(FunctionType::new( type_row![], diff --git a/hugr-passes/src/merge_bbs.rs b/hugr-passes/src/merge_bbs.rs index 7d1cf9d52..a1116ca16 100644 --- a/hugr-passes/src/merge_bbs.rs +++ b/hugr-passes/src/merge_bbs.rs @@ -197,7 +197,7 @@ mod test { fn lifted_unary_unit_sum + AsRef, T>(b: &mut DFGWrapper) -> Wire { let lc = b.add_load_value(Value::unary_unit_sum()); let lift = b - .add_dataflow_op(Lift::new(Type::new_unit_sum(1).into(), PRELUDE_ID), [lc]) + .add_dataflow_op(Lift::new(type_row![Type::new_unit_sum(1)], PRELUDE_ID), [lc]) .unwrap(); let [w] = lift.outputs_arr(); w From 28431c4e509202b8fd4c44ff0e3b3ee5745f8dfc Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Mon, 10 Jun 2024 17:16:25 +0100 Subject: [PATCH 046/115] Remove Signature --Into--> FunctionType, fix 5 errors reported --> many more --- hugr-core/src/extension/op_def.rs | 2 +- hugr-core/src/ops/constant.rs | 2 +- hugr-core/src/ops/dataflow.rs | 4 ++-- hugr-core/src/types/poly_func.rs | 2 +- hugr-core/src/types/signature.rs | 7 ------- 5 files changed, 5 insertions(+), 12 deletions(-) diff --git a/hugr-core/src/extension/op_def.rs b/hugr-core/src/extension/op_def.rs index c8fad2c47..b42d45905 100644 --- a/hugr-core/src/extension/op_def.rs +++ b/hugr-core/src/extension/op_def.rs @@ -200,7 +200,7 @@ impl From for SignatureFunc { impl From for SignatureFunc { fn from(v: Signature) -> Self { - Self::TypeScheme(CustomValidator::from_polyfunc(FunctionType::::from(v))) + Self::TypeScheme(CustomValidator::from_polyfunc(v)) } } diff --git a/hugr-core/src/ops/constant.rs b/hugr-core/src/ops/constant.rs index 7950a2205..eefe23d56 100644 --- a/hugr-core/src/ops/constant.rs +++ b/hugr-core/src/ops/constant.rs @@ -287,7 +287,7 @@ impl Value { Self::Sum { sum_type, .. } => sum_type.clone().into(), Self::Function { hugr } => { let func_type = mono_fn_type(hugr).unwrap_or_else(|e| panic!("{}", e)); - Type::new_function(func_type) + Type::new_function(func_type.into_()) } } } diff --git a/hugr-core/src/ops/dataflow.rs b/hugr-core/src/ops/dataflow.rs index 55f2f78e9..41b6db807 100644 --- a/hugr-core/src/ops/dataflow.rs +++ b/hugr-core/src/ops/dataflow.rs @@ -268,7 +268,7 @@ impl DataflowOpTrait for CallIndirect { let mut s = self.signature.clone(); s.input .to_mut() - .insert(0, Type::new_function(self.signature.clone())); + .insert(0, Type::new_function(self.signature.clone().into_())); s } } @@ -360,7 +360,7 @@ impl LoadFunction { exts: &ExtensionRegistry, ) -> Result { let type_args = type_args.into(); - let instantiation = func_sig.instantiate(&type_args, exts)?; + let instantiation = func_sig.instantiate(&type_args, exts)?.into_(); let signature = FunctionType::new(TypeRow::new(), vec![Type::new_function(instantiation)]); Ok(Self { func_sig, diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index 40983327f..1e9f34e72 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -53,7 +53,7 @@ impl From> for PolyFuncType { fn from(value: PolyFuncType) -> Self { Self { params: value.params, - body: value.body.into() + body: value.body.into_() } } } diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index 18adc7827..e39095837 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -255,13 +255,6 @@ impl TryFrom for Signature { } } -impl From for FunctionType { - fn from(value: Signature) -> Self { - Self::new(value.input.into_(), value.output.into_()) - .with_extension_delta(value.extension_reqs) - } -} - impl PartialEq for Signature { fn eq(&self, other: &FunctionType) -> bool { self.input == other.input From 2f627cdcfca4fcb1786d7c2de294c444b0f86928 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Mon, 10 Jun 2024 18:34:58 +0100 Subject: [PATCH 047/115] Don't double-var w/assert TypeRow-from-Type: causes type-annots-reqd --- hugr-core/src/types/type_row.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/hugr-core/src/types/type_row.rs b/hugr-core/src/types/type_row.rs index 1d055590c..194267a24 100644 --- a/hugr-core/src/types/type_row.rs +++ b/hugr-core/src/types/type_row.rs @@ -184,15 +184,22 @@ impl From<&'static [Type]> for TypeRow { } } -impl From> for TypeRow { +impl From> for TypeRow { fn from(t: Type) -> Self { - let _ = Implies::::A_IMPLIES_B; Self { types: vec![t.into_()].into(), } } } +impl From for TypeRow { + fn from(t: Type) -> Self { + Self { + types: vec![t].into() + } + } +} + impl Deref for TypeRow { type Target = [Type]; From 67319859f51521974871c2c3e5e63a0538b3e6c8 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 11 Jun 2024 09:35:11 +0100 Subject: [PATCH 048/115] FunctionType::into_ is not polymorphic; we don't expect parametrization over FTs --- hugr-core/src/types/signature.rs | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index e39095837..b4b406949 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -5,7 +5,7 @@ use itertools::Either; use std::fmt::{self, Display, Write}; use super::type_param::TypeParam; -use super::{Implies, Substitution, Type, TypeBound, TypeEnum, TypeRow}; +use super::{Substitution, Type, TypeBound, TypeEnum, TypeRow}; use crate::core::PortIndex; use crate::extension::{ExtensionRegistry, ExtensionSet, SignatureError}; @@ -94,15 +94,6 @@ impl FunctionType { self.output.validate(extension_registry, var_decls)?; self.extension_reqs.validate(var_decls) } - - pub(crate) fn into_(self) -> FunctionType { - let _ = Implies::::A_IMPLIES_B; - FunctionType { - input: self.input.into_(), - output: self.output.into_(), - extension_reqs: self.extension_reqs - } - } } impl FunctionType { @@ -119,6 +110,14 @@ impl FunctionType { } impl Signature { + pub(crate) fn into_(self) -> FunctionType { + FunctionType { + input: self.input.into_(), + output: self.output.into_(), + extension_reqs: self.extension_reqs + } + } + /// Returns the type of a value [`Port`]. Returns `None` if the port is out /// of bounds. #[inline] From 9e4e4a2f350f59c3cda5f47b96575add103d7138 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 11 Jun 2024 09:36:52 +0100 Subject: [PATCH 049/115] ...and remove flexibility in FunctionType --Into-> PolyFuncType --- hugr-core/src/extension/op_def.rs | 2 +- hugr-core/src/types/poly_func.rs | 9 ++++----- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/hugr-core/src/extension/op_def.rs b/hugr-core/src/extension/op_def.rs index b42d45905..312d8459f 100644 --- a/hugr-core/src/extension/op_def.rs +++ b/hugr-core/src/extension/op_def.rs @@ -200,7 +200,7 @@ impl From for SignatureFunc { impl From for SignatureFunc { fn from(v: Signature) -> Self { - Self::TypeScheme(CustomValidator::from_polyfunc(v)) + Self::TypeScheme(CustomValidator::from_polyfunc(v.into_())) } } diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index 1e9f34e72..ee9ee6cc6 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -9,7 +9,7 @@ use { proptest_derive::Arbitrary, }; -use super::{signature::FunctionType, Implies}; +use super::{signature::FunctionType}; use super::type_param::{check_type_args, TypeArg, TypeParam}; use super::Substitution; @@ -39,12 +39,11 @@ pub struct PolyFuncType { body: FunctionType, } -impl From> for PolyFuncType { - fn from(body: FunctionType) -> Self { - let _ = Implies::::A_IMPLIES_B; +impl From> for PolyFuncType { + fn from(body: FunctionType) -> Self { Self { params: vec![], - body: body.into_(), + body } } } From f47ad714fa5859e4c4a8208647a55ffe27d5a1a0 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 11 Jun 2024 09:42:45 +0100 Subject: [PATCH 050/115] Reinstate FuncTypeBase; FunctionType is thus always :: --- hugr-core/src/hugr/views.rs | 2 +- hugr-core/src/std_extensions/logic.rs | 2 +- hugr-core/src/types.rs | 2 +- hugr-core/src/types/poly_func.rs | 16 ++++++++-------- hugr-core/src/types/serialize.rs | 2 +- hugr-core/src/types/signature.rs | 14 ++++++++------ 6 files changed, 20 insertions(+), 18 deletions(-) diff --git a/hugr-core/src/hugr/views.rs b/hugr-core/src/hugr/views.rs index 174b879f4..2546c7b1c 100644 --- a/hugr-core/src/hugr/views.rs +++ b/hugr-core/src/hugr/views.rs @@ -340,7 +340,7 @@ pub trait HugrView: HugrInternals { /// /// In contrast to [`get_function_type`][HugrView::get_function_type], this /// method always return a concrete [`FunctionType`]. - fn get_df_function_type(&self) -> Option> { + fn get_df_function_type(&self) -> Option { let op = self.get_optype(self.root()); op.inner_function_type() } diff --git a/hugr-core/src/std_extensions/logic.rs b/hugr-core/src/std_extensions/logic.rs index 995db6702..2621b8f87 100644 --- a/hugr-core/src/std_extensions/logic.rs +++ b/hugr-core/src/std_extensions/logic.rs @@ -160,7 +160,7 @@ fn logic_op_sig() -> impl SignatureFromArgs { return Err(SignatureError::InvalidTypeArgs); }; let var_arg_row = vec![BOOL_T; n as usize]; - Ok(FunctionType::::new(var_arg_row, vec![BOOL_T]).into()) + Ok(FunctionType::new(var_arg_row, vec![BOOL_T]).into()) } fn static_params(&self) -> &[TypeParam] { diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index df3191485..a483960f3 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -298,7 +298,7 @@ impl Type { const EMPTY_TYPEROW_REF: &'static TypeRow = &Self::EMPTY_TYPEROW; /// Initialize a new function type. - pub fn new_function(fun_ty: impl Into>) -> Self { + pub fn new_function(fun_ty: impl Into) -> Self { Self::new(TypeEnum::Function(Box::new(fun_ty.into()))) } diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index ee9ee6cc6..96a11e525 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -9,7 +9,7 @@ use { proptest_derive::Arbitrary, }; -use super::{signature::FunctionType}; +use super::signature::{FuncTypeBase, FunctionType}; use super::type_param::{check_type_args, TypeArg, TypeParam}; use super::Substitution; @@ -36,11 +36,11 @@ pub struct PolyFuncType { params: Vec, /// Template for the function. May contain variables up to length of [Self::params] #[cfg_attr(test, proptest(strategy = "any_with::(params)"))] - body: FunctionType, + body: FuncTypeBase, } -impl From> for PolyFuncType { - fn from(body: FunctionType) -> Self { +impl From> for PolyFuncType { + fn from(body: FuncTypeBase) -> Self { Self { params: vec![], body @@ -57,7 +57,7 @@ impl From> for PolyFuncType { } } -impl TryFrom> for FunctionType { +impl TryFrom> for FuncTypeBase { /// If the PolyFuncType is not monomorphic, fail with its binders type Error = Vec; @@ -77,13 +77,13 @@ impl PolyFuncType { } /// The body of the type, a function type. - pub fn body(&self) -> &FunctionType { + pub fn body(&self) -> &FuncTypeBase { &self.body } /// Create a new PolyFuncType given the kinds of the variables it declares /// and the underlying function type. - pub fn new(params: impl Into>, body: FunctionType) -> Self { + pub fn new(params: impl Into>, body: FuncTypeBase) -> Self { Self { params: params.into(), body @@ -100,7 +100,7 @@ impl PolyFuncType { &self, args: &[TypeArg], ext_reg: &ExtensionRegistry, - ) -> Result, SignatureError> { + ) -> Result, SignatureError> { // Check that args are applicable, and that we have a value for each binder, // i.e. each possible free variable within the body. check_type_args(args, &self.params)?; diff --git a/hugr-core/src/types/serialize.rs b/hugr-core/src/types/serialize.rs index 4c25dd94b..d2f11277c 100644 --- a/hugr-core/src/types/serialize.rs +++ b/hugr-core/src/types/serialize.rs @@ -11,7 +11,7 @@ use crate::ops::AliasDecl; pub(super) enum SerSimpleType { Q, I, - G(Box>), + G(Box), Sum(SumType), Array { inner: Box, len: u64 }, Opaque(CustomType), diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index b4b406949..e7146e139 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -23,7 +23,7 @@ use {crate::proptest::RecursionDepth, ::proptest::prelude::*, proptest_derive::A /// /// [Graph]: crate::ops::constant::Value::Function /// [RowVariable]: crate::types::TypeEnum::RowVariable -pub struct FunctionType { +pub struct FuncTypeBase { /// Value inputs of the function. #[cfg_attr(test, proptest(strategy = "any_with::(params)"))] pub input: TypeRow, @@ -36,9 +36,11 @@ pub struct FunctionType { /// The concept of "signature" in the spec - the edges required to/from a node or graph /// and also the target (value) of a call (static). -pub type Signature = FunctionType; +pub type Signature = FuncTypeBase; -impl FunctionType { +pub type FunctionType = FuncTypeBase; + +impl FuncTypeBase { /// Builder method, add extension_reqs to an FunctionType pub fn with_extension_delta(mut self, rs: impl Into) -> Self { self.extension_reqs = self.extension_reqs.union(rs.into()); @@ -96,7 +98,7 @@ impl FunctionType { } } -impl FunctionType { +impl FunctionType { /// If this FunctionType contains any row variables, return one. pub fn find_rowvar(&self) -> Option<(usize, TypeBound)> { self.input @@ -110,7 +112,7 @@ impl FunctionType { } impl Signature { - pub(crate) fn into_(self) -> FunctionType { + pub(crate) fn into_(self) -> FunctionType { FunctionType { input: self.input.into_(), output: self.output.into_(), @@ -231,7 +233,7 @@ impl Signature { } } -impl Display for FunctionType { +impl Display for FuncTypeBase { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if !self.input.is_empty() { self.input.fmt(f)?; From 59f599dfcf3aa6a27a8a447bd927a2a05186cdd9 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 11 Jun 2024 10:13:22 +0100 Subject: [PATCH 051/115] RIP Signature; FunctionType and FunTypeVarArgs. Note: maybe convert in PFT::new? --- hugr-core/src/builder.rs | 4 +- hugr-core/src/builder/build_traits.rs | 6 +-- hugr-core/src/builder/cfg.rs | 6 +-- hugr-core/src/builder/conditional.rs | 4 +- hugr-core/src/builder/dataflow.rs | 6 +-- hugr-core/src/builder/tail_loop.rs | 4 +- hugr-core/src/extension.rs | 14 +++--- .../src/extension/declarative/signature.rs | 4 +- hugr-core/src/extension/infer/test.rs | 8 ++-- hugr-core/src/extension/op_def.rs | 16 +++---- hugr-core/src/extension/prelude.rs | 6 +-- hugr-core/src/hugr.rs | 4 +- hugr-core/src/hugr/rewrite/replace.rs | 2 +- hugr-core/src/hugr/views.rs | 6 +-- hugr-core/src/hugr/views/sibling_subgraph.rs | 4 +- hugr-core/src/ops.rs | 8 ++-- hugr-core/src/ops/constant.rs | 4 +- hugr-core/src/ops/controlflow.rs | 16 +++---- hugr-core/src/ops/custom.rs | 20 ++++----- hugr-core/src/ops/dataflow.rs | 44 +++++++++---------- hugr-core/src/ops/leaf.rs | 11 +++-- hugr-core/src/ops/module.rs | 8 ++-- .../std_extensions/arithmetic/conversions.rs | 8 ++-- .../src/std_extensions/arithmetic/int_ops.rs | 6 +-- hugr-core/src/std_extensions/collections.rs | 8 ++-- hugr-core/src/std_extensions/logic.rs | 4 +- hugr-core/src/types.rs | 6 +-- hugr-core/src/types/serialize.rs | 4 +- hugr-core/src/types/signature.rs | 24 +++++----- hugr-py/src/hugr/serialization/tys.py | 4 +- 30 files changed, 135 insertions(+), 134 deletions(-) diff --git a/hugr-core/src/builder.rs b/hugr-core/src/builder.rs index d5633f92c..f0f046a7a 100644 --- a/hugr-core/src/builder.rs +++ b/hugr-core/src/builder.rs @@ -222,7 +222,7 @@ pub(crate) mod test { use crate::hugr::{views::HugrView, HugrMut, NodeType}; use crate::ops; - use crate::types::{FunctionType, PolyFuncType, Signature, Type}; + use crate::types::{FunctionType, PolyFuncType, Type}; use crate::{type_row, Hugr}; use super::handle::BuildHandle; @@ -275,7 +275,7 @@ pub(crate) mod test { /// for tests which want to avoid having open extension variables after /// inference. Using DFGBuilder will default to a root node with an open /// extension variable - pub(crate) fn closed_dfg_root_hugr(signature: Signature) -> Hugr { + pub(crate) fn closed_dfg_root_hugr(signature: FunctionType) -> Hugr { let mut hugr = Hugr::new(NodeType::new_pure(ops::DFG { signature: signature.clone(), })); diff --git a/hugr-core/src/builder/build_traits.rs b/hugr-core/src/builder/build_traits.rs index 87e7aa70d..a3285e30f 100644 --- a/hugr-core/src/builder/build_traits.rs +++ b/hugr-core/src/builder/build_traits.rs @@ -20,7 +20,7 @@ use crate::{ }; use crate::extension::{ExtensionRegistry, ExtensionSet, PRELUDE_REGISTRY}; -use crate::types::{PolyFuncType, Signature, Type, TypeArg, TypeRow}; +use crate::types::{PolyFuncType, FunctionType, Type, TypeArg, TypeRow}; use itertools::Itertools; @@ -296,7 +296,7 @@ pub trait Dataflow: Container { // TODO: Should this be one function, or should there be a temporary "op" one like with the others? fn dfg_builder( &mut self, - signature: Signature, + signature: FunctionType, input_extensions: Option, input_wires: impl IntoIterator, ) -> Result, BuildError> { @@ -334,7 +334,7 @@ pub trait Dataflow: Container { self, NodeType::new( ops::CFG { - signature: Signature::new(inputs.clone(), output_types.clone()) + signature: FunctionType::new(inputs.clone(), output_types.clone()) .with_extension_delta(extension_delta), }, input_extensions.into(), diff --git a/hugr-core/src/builder/cfg.rs b/hugr-core/src/builder/cfg.rs index 7704f95ef..f1a02024e 100644 --- a/hugr-core/src/builder/cfg.rs +++ b/hugr-core/src/builder/cfg.rs @@ -9,7 +9,7 @@ use crate::extension::{ExtensionRegistry, ExtensionSet}; use crate::{hugr::views::HugrView, types::TypeRow}; use crate::{ ops::{self, handle::NodeHandle, DataflowBlock, DataflowParent, ExitBlock, OpType}, - types::Signature, + types::FunctionType, }; use crate::Node; @@ -153,7 +153,7 @@ impl + AsRef> SubContainer for CFGBuilder { impl CFGBuilder { /// New CFG rooted HUGR builder - pub fn new(signature: Signature) -> Result { + pub fn new(signature: FunctionType) -> Result { let cfg_op = ops::CFG { signature: signature.clone(), }; @@ -251,7 +251,7 @@ impl + AsRef> CFGBuilder { /// This function will return an error if there is an error adding the node. pub fn simple_block_builder( &mut self, - signature: Signature, + signature: FunctionType, n_cases: usize, ) -> Result, BuildError> { self.block_builder( diff --git a/hugr-core/src/builder/conditional.rs b/hugr-core/src/builder/conditional.rs index 252ee3193..e39c88451 100644 --- a/hugr-core/src/builder/conditional.rs +++ b/hugr-core/src/builder/conditional.rs @@ -1,7 +1,7 @@ use crate::extension::ExtensionRegistry; use crate::hugr::views::HugrView; use crate::ops::dataflow::DataflowOpTrait; -use crate::types::{FunctionType, Signature, TypeRow}; +use crate::types::{FunctionType, TypeRow}; use crate::ops; use crate::ops::handle::CaseID; @@ -192,7 +192,7 @@ impl ConditionalBuilder { impl CaseBuilder { /// Initialize a Case rooted HUGR - pub fn new(signature: Signature) -> Result { + pub fn new(signature: FunctionType) -> Result { let op = ops::Case { signature: signature.clone(), }; diff --git a/hugr-core/src/builder/dataflow.rs b/hugr-core/src/builder/dataflow.rs index cbde241df..626227ce5 100644 --- a/hugr-core/src/builder/dataflow.rs +++ b/hugr-core/src/builder/dataflow.rs @@ -7,7 +7,7 @@ use std::marker::PhantomData; use crate::hugr::{HugrView, NodeType, ValidationError}; use crate::ops; -use crate::types::{PolyFuncType, Signature}; +use crate::types::{PolyFuncType, FunctionType}; use crate::extension::{ExtensionRegistry, ExtensionSet}; use crate::Node; @@ -26,7 +26,7 @@ impl + AsRef> DFGBuilder { pub(super) fn create_with_io( mut base: T, parent: Node, - signature: Signature, + signature: FunctionType, input_extensions: Option, ) -> Result { let num_in_wires = signature.input().len(); @@ -75,7 +75,7 @@ impl DFGBuilder { /// # Errors /// /// Error in adding DFG child nodes. - pub fn new(signature: Signature) -> Result, BuildError> { + pub fn new(signature: FunctionType) -> Result, BuildError> { let dfg_op = ops::DFG { signature: signature.clone(), }; diff --git a/hugr-core/src/builder/tail_loop.rs b/hugr-core/src/builder/tail_loop.rs index 4c4a60218..52c9ecd2d 100644 --- a/hugr-core/src/builder/tail_loop.rs +++ b/hugr-core/src/builder/tail_loop.rs @@ -1,7 +1,7 @@ use crate::ops; use crate::hugr::{views::HugrView, NodeType}; -use crate::types::{Signature, TypeRow}; +use crate::types::{FunctionType, TypeRow}; use crate::{Hugr, Node}; use super::build_traits::SubContainer; @@ -20,7 +20,7 @@ impl + AsRef> TailLoopBuilder { loop_node: Node, tail_loop: &ops::TailLoop, ) -> Result { - let signature = Signature::new(tail_loop.body_input_row(), tail_loop.body_output_row()); + let signature = FunctionType::new(tail_loop.body_input_row(), tail_loop.body_output_row()); let dfg_build = DFGBuilder::create_with_io(base, loop_node, signature, None)?; Ok(TailLoopBuilder::from_dfg_builder(dfg_build)) diff --git a/hugr-core/src/extension.rs b/hugr-core/src/extension.rs index c645b5f21..fa24679d6 100644 --- a/hugr-core/src/extension.rs +++ b/hugr-core/src/extension.rs @@ -16,7 +16,7 @@ use crate::ops::constant::{ValueName, ValueNameRef}; use crate::ops::custom::{ExtensionOp, OpaqueOp}; use crate::ops::{self, OpName, OpNameRef}; use crate::types::type_param::{TypeArg, TypeArgError, TypeParam}; -use crate::types::Signature; +use crate::types::FunctionType; use crate::types::TypeNameRef; use crate::types::{check_typevar_decl, CustomType, Substitution, TypeBound, TypeName}; @@ -141,10 +141,10 @@ pub enum SignatureError { /// Invalid type arguments #[error("Invalid type arguments for operation")] InvalidTypeArgs, - /// The Extension Registry did not contain an Extension referenced by the Signature + /// The Extension Registry did not contain an Extension referenced by the FunctionType #[error("Extension '{0}' not found")] ExtensionNotFound(ExtensionId), - /// The Extension was found in the registry, but did not contain the Type(Def) referenced in the Signature + /// The Extension was found in the registry, but did not contain the Type(Def) referenced in the FunctionType #[error("Extension '{exn}' did not contain expected TypeDef '{typ}'")] ExtensionTypeNotFound { exn: ExtensionId, typ: TypeName }, /// The bound recorded for a CustomType doesn't match what the TypeDef would compute @@ -173,8 +173,8 @@ pub enum SignatureError { "Incorrect result of type application in Call - cached {cached} but expected {expected}" )] CallIncorrectlyAppliesType { - cached: Signature, - expected: Signature, + cached: FunctionType, + expected: FunctionType, }, /// The result of the type application stored in a [LoadFunction] /// is not what we get by applying the type-args to the polymorphic function @@ -184,8 +184,8 @@ pub enum SignatureError { "Incorrect result of type application in LoadFunction - cached {cached} but expected {expected}" )] LoadFunctionIncorrectlyAppliesType { - cached: Signature, - expected: Signature, + cached: FunctionType, + expected: FunctionType, }, } diff --git a/hugr-core/src/extension/declarative/signature.rs b/hugr-core/src/extension/declarative/signature.rs index f8482b6b4..5ac1de0c4 100644 --- a/hugr-core/src/extension/declarative/signature.rs +++ b/hugr-core/src/extension/declarative/signature.rs @@ -14,7 +14,7 @@ use smol_str::SmolStr; use crate::extension::prelude::PRELUDE_ID; use crate::extension::{CustomValidator, ExtensionSet, SignatureFunc, TypeDef}; use crate::types::type_param::TypeParam; -use crate::types::{CustomType, FunctionType, PolyFuncType, Type, TypeRow}; +use crate::types::{CustomType, FunTypeVarArgs, PolyFuncType, Type, TypeRow}; use crate::Extension; use super::{DeclarationContext, ExtensionDeclarationError}; @@ -50,7 +50,7 @@ impl SignatureDeclaration { Ok(types.into()) }; - let body = FunctionType { + let body = FunTypeVarArgs { input: make_type_row(&self.inputs)?, output: make_type_row(&self.outputs)?, extension_reqs: self.extensions.clone(), diff --git a/hugr-core/src/extension/infer/test.rs b/hugr-core/src/extension/infer/test.rs index e2aa1f86d..73ef8289d 100644 --- a/hugr-core/src/extension/infer/test.rs +++ b/hugr-core/src/extension/infer/test.rs @@ -21,7 +21,7 @@ use crate::{ }; use crate::type_row; -use crate::types::{FunctionType, Signature, Type, TypeRow}; +use crate::types::{FunctionType, Type, TypeRow}; use cool_asserts::assert_matches; use itertools::Itertools; @@ -281,7 +281,7 @@ fn create_with_io( hugr: &mut Hugr, parent: Node, op: impl Into, - op_sig: Signature, + op_sig: FunctionType, ) -> Result<[Node; 3], Box> { let op: OpType = op.into(); @@ -438,7 +438,7 @@ fn extension_adding_sequence() -> Result<(), Box> { Ok(()) } -fn make_opaque(extension: impl Into, signature: Signature) -> CustomOp { +fn make_opaque(extension: impl Into, signature: FunctionType) -> CustomOp { ops::custom::OpaqueOp::new(extension.into(), "", "".into(), vec![], signature).into() } @@ -1002,7 +1002,7 @@ fn sccs() { #[test] /// Note: This test is relying on the builder's `define_function` doing the -/// right thing: it takes input resources via a [`Signature`], which it passes +/// right thing: it takes input resources via a [`FunctionType`], which it passes /// to `create_with_io`, creating concrete resource sets. /// Inference can still fail for a valid FuncDefn hugr created without using /// the builder API. diff --git a/hugr-core/src/extension/op_def.rs b/hugr-core/src/extension/op_def.rs index 312d8459f..d99a4319a 100644 --- a/hugr-core/src/extension/op_def.rs +++ b/hugr-core/src/extension/op_def.rs @@ -11,7 +11,7 @@ use super::{ use crate::ops::{OpName, OpNameRef}; use crate::types::type_param::{check_type_args, TypeArg, TypeParam}; -use crate::types::{FunctionType, PolyFuncType, Signature}; +use crate::types::{FunTypeVarArgs, FunctionType, PolyFuncType}; use crate::Hugr; /// Trait necessary for binary computations of OpDef signature @@ -147,7 +147,7 @@ impl CustomValidator { } } -/// The two ways in which an OpDef may compute the Signature of each operation node. +/// The two ways in which an OpDef may compute the FunctionType of each operation node. #[derive(serde::Deserialize, serde::Serialize)] pub enum SignatureFunc { // Note: except for serialization, we could have type schemes just implement the same @@ -192,14 +192,14 @@ impl From for SignatureFunc { } } -impl From for SignatureFunc { - fn from(v: FunctionType) -> Self { +impl From for SignatureFunc { + fn from(v: FunTypeVarArgs) -> Self { Self::TypeScheme(CustomValidator::from_polyfunc(v)) } } -impl From for SignatureFunc { - fn from(v: Signature) -> Self { +impl From for SignatureFunc { + fn from(v: FunctionType) -> Self { Self::TypeScheme(CustomValidator::from_polyfunc(v.into_())) } } @@ -234,7 +234,7 @@ impl SignatureFunc { def: &OpDef, args: &[TypeArg], exts: &ExtensionRegistry, - ) -> Result { + ) -> Result { let temp: PolyFuncType; let (pf, args) = match &self { SignatureFunc::TypeScheme(custom) => { @@ -364,7 +364,7 @@ impl OpDef { &self, args: &[TypeArg], exts: &ExtensionRegistry, - ) -> Result { + ) -> Result { self.signature_func.compute_signature(self, args, exts) } diff --git a/hugr-core/src/extension/prelude.rs b/hugr-core/src/extension/prelude.rs index 932bcda58..a20201250 100644 --- a/hugr-core/src/extension/prelude.rs +++ b/hugr-core/src/extension/prelude.rs @@ -4,7 +4,7 @@ use lazy_static::lazy_static; use crate::ops::constant::ValueName; use crate::ops::{CustomOp, OpName}; -use crate::types::{SumType, TypeName}; +use crate::types::{FunTypeVarArgs, SumType, TypeName}; use crate::{ extension::{ExtensionId, TypeDefBound}, ops::constant::CustomConst, @@ -32,7 +32,7 @@ impl SignatureFromArgs for ArrayOpCustom { Ok(PolyFuncType::new( vec![TypeBound::Any.into()], - FunctionType::new(var_arg_row, other_row), + FunTypeVarArgs::new(var_arg_row, other_row), )) } @@ -67,7 +67,7 @@ impl SignatureFromArgs for GenericOpCustom { }; outs.push(ty.clone()); } - Ok(PolyFuncType::new(vec![], FunctionType::new(inps, outs))) + Ok(FunTypeVarArgs::new(inps, outs).into()) } fn static_params(&self) -> &[TypeParam] { diff --git a/hugr-core/src/hugr.rs b/hugr-core/src/hugr.rs index 0d026db53..f54e56655 100644 --- a/hugr-core/src/hugr.rs +++ b/hugr-core/src/hugr.rs @@ -31,7 +31,7 @@ use crate::extension::infer_extensions; use crate::extension::{ExtensionRegistry, ExtensionSet, ExtensionSolution, InferExtensionError}; use crate::ops::custom::resolve_extension_ops; use crate::ops::{OpTag, OpTrait, OpType, DEFAULT_OPTYPE}; -use crate::types::Signature; +use crate::types::FunctionType; use crate::{Direction, Node}; use delegate::delegate; @@ -109,7 +109,7 @@ impl NodeType { } /// Get the function type from the embedded op - pub fn op_signature(&self) -> Option { + pub fn op_signature(&self) -> Option { self.op.dataflow_signature() } diff --git a/hugr-core/src/hugr/rewrite/replace.rs b/hugr-core/src/hugr/rewrite/replace.rs index 9cc028053..495c4a97a 100644 --- a/hugr-core/src/hugr/rewrite/replace.rs +++ b/hugr-core/src/hugr/rewrite/replace.rs @@ -161,7 +161,7 @@ impl Replacement { .ok_or(ReplaceError::CantReplaceRoot)?; // If no parent // Check replacement parent is of same tag. Note we do not require exact equality - // of OpType/Signature, e.g. to ease changing of Input/Output node signatures too. + // of OpType/FunctionType, e.g. to ease changing of Input/Output node signatures too. let removed = h.get_optype(parent).tag(); let replacement = self.replacement.root_type().tag(); if removed != replacement { diff --git a/hugr-core/src/hugr/views.rs b/hugr-core/src/hugr/views.rs index 2546c7b1c..2c48e0853 100644 --- a/hugr-core/src/hugr/views.rs +++ b/hugr-core/src/hugr/views.rs @@ -32,7 +32,7 @@ use crate::extension::ExtensionRegistry; use crate::ops::handle::NodeHandle; use crate::ops::{OpParent, OpTag, OpTrait, OpType}; -use crate::types::{EdgeKind, FunctionType, Signature}; +use crate::types::{EdgeKind, FunctionType}; use crate::types::{PolyFuncType, Type}; use crate::{Direction, IncomingPort, Node, OutgoingPort, Port}; @@ -340,7 +340,7 @@ pub trait HugrView: HugrInternals { /// /// In contrast to [`get_function_type`][HugrView::get_function_type], this /// method always return a concrete [`FunctionType`]. - fn get_df_function_type(&self) -> Option { + fn get_df_function_type(&self) -> Option { let op = self.get_optype(self.root()); op.inner_function_type() } @@ -439,7 +439,7 @@ pub trait HugrView: HugrInternals { /// Get the "signature" (incoming and outgoing types) of a node, non-Value /// kind ports will be missing. - fn signature(&self, node: Node) -> Option { + fn signature(&self, node: Node) -> Option { self.get_optype(node).dataflow_signature() } diff --git a/hugr-core/src/hugr/views/sibling_subgraph.rs b/hugr-core/src/hugr/views/sibling_subgraph.rs index 0203f6a48..ddc307509 100644 --- a/hugr-core/src/hugr/views/sibling_subgraph.rs +++ b/hugr-core/src/hugr/views/sibling_subgraph.rs @@ -22,7 +22,7 @@ use crate::hugr::{HugrMut, HugrView, RootTagged}; use crate::ops::dataflow::DataflowOpTrait; use crate::ops::handle::{ContainerHandle, DataflowOpID}; use crate::ops::{OpTag, OpTrait}; -use crate::types::{FunctionType, Signature, Type}; +use crate::types::{FunctionType, Type}; use crate::{Hugr, IncomingPort, Node, OutgoingPort, Port, SimpleReplacement}; /// A non-empty convex subgraph of a HUGR sibling graph. @@ -289,7 +289,7 @@ impl SiblingSubgraph { } /// The signature of the subgraph. - pub fn signature(&self, hugr: &impl HugrView) -> Signature { + pub fn signature(&self, hugr: &impl HugrView) -> FunctionType { let input = self .inputs .iter() diff --git a/hugr-core/src/ops.rs b/hugr-core/src/ops.rs index 668216de7..2e48d1f9d 100644 --- a/hugr-core/src/ops.rs +++ b/hugr-core/src/ops.rs @@ -10,7 +10,7 @@ pub mod module; pub mod tag; pub mod validate; use crate::extension::ExtensionSet; -use crate::types::{EdgeKind, Signature}; +use crate::types::{EdgeKind, FunctionType}; use crate::{Direction, OutgoingPort, Port}; use crate::{IncomingPort, PortIndex}; use paste::paste; @@ -342,7 +342,7 @@ pub trait OpTrait { /// The signature of the operation. /// /// Only dataflow operations have a signature, otherwise returns None. - fn dataflow_signature(&self) -> Option { + fn dataflow_signature(&self) -> Option { None } @@ -405,13 +405,13 @@ pub trait OpParent { /// sibling graph. /// /// Non-container ops like `FuncDecl` return `None` even though they represent a function. - fn inner_function_type(&self) -> Option { + fn inner_function_type(&self) -> Option { None } } impl OpParent for T { - fn inner_function_type(&self) -> Option { + fn inner_function_type(&self) -> Option { Some(DataflowParent::inner_signature(self)) } } diff --git a/hugr-core/src/ops/constant.rs b/hugr-core/src/ops/constant.rs index eefe23d56..1942d8a3f 100644 --- a/hugr-core/src/ops/constant.rs +++ b/hugr-core/src/ops/constant.rs @@ -5,7 +5,7 @@ mod custom; use super::{NamedOp, OpName, OpTrait, StaticTag}; use super::{OpTag, OpType}; use crate::extension::ExtensionSet; -use crate::types::{CustomType, EdgeKind, Signature, SumType, SumTypeError, Type}; +use crate::types::{CustomType, EdgeKind, FunctionType, SumType, SumTypeError, Type}; use crate::{Hugr, HugrView}; use delegate::delegate; @@ -267,7 +267,7 @@ pub enum ConstTypeError { } /// Hugrs (even functions) inside Consts must be monomorphic -fn mono_fn_type(h: &Hugr) -> Result { +fn mono_fn_type(h: &Hugr) -> Result { if let Some(pf) = h.get_function_type() { if let Ok(ft) = pf.try_into() { return Ok(ft); diff --git a/hugr-core/src/ops/controlflow.rs b/hugr-core/src/ops/controlflow.rs index e109961d7..f4f8024f4 100644 --- a/hugr-core/src/ops/controlflow.rs +++ b/hugr-core/src/ops/controlflow.rs @@ -1,7 +1,7 @@ //! Control flow operations. use crate::extension::ExtensionSet; -use crate::types::{EdgeKind, FunctionType, Signature, Type, TypeRow}; +use crate::types::{EdgeKind, FunctionType, Type, TypeRow}; use crate::Direction; use super::dataflow::{DataflowOpTrait, DataflowParent}; @@ -29,7 +29,7 @@ impl DataflowOpTrait for TailLoop { "A tail-controlled loop" } - fn signature(&self) -> Signature { + fn signature(&self) -> FunctionType { let [inputs, outputs] = [&self.just_inputs, &self.just_outputs].map(|row| row.extend(self.rest.iter())); FunctionType::new(inputs, outputs) @@ -73,7 +73,7 @@ impl DataflowOpTrait for Conditional { "HUGR conditional operation" } - fn signature(&self) -> Signature { + fn signature(&self) -> FunctionType { let mut inputs = self.other_inputs.clone(); inputs .to_mut() @@ -95,7 +95,7 @@ impl Conditional { #[allow(missing_docs)] #[cfg_attr(test, derive(proptest_derive::Arbitrary))] pub struct CFG { - pub signature: Signature, + pub signature: FunctionType, } impl_op_name!(CFG); @@ -107,7 +107,7 @@ impl DataflowOpTrait for CFG { "A dataflow node defined by a child CFG" } - fn signature(&self) -> Signature { + fn signature(&self) -> FunctionType { self.signature.clone() } } @@ -153,7 +153,7 @@ impl StaticTag for ExitBlock { } impl DataflowParent for DataflowBlock { - fn inner_signature(&self) -> Signature { + fn inner_signature(&self) -> FunctionType { // The node outputs a Sum before the data outputs of the block node let sum_type = Type::new_sum(self.sum_rows.iter().cloned()); let mut node_outputs = vec![sum_type]; @@ -250,7 +250,7 @@ impl BasicBlock for ExitBlock { /// Case ops - nodes valid inside Conditional nodes. pub struct Case { /// The signature of the contained dataflow graph. - pub signature: Signature, + pub signature: FunctionType, } impl_op_name!(Case); @@ -260,7 +260,7 @@ impl StaticTag for Case { } impl DataflowParent for Case { - fn inner_signature(&self) -> Signature { + fn inner_signature(&self) -> FunctionType { self.signature.clone() } } diff --git a/hugr-core/src/ops/custom.rs b/hugr-core/src/ops/custom.rs index cc49f147e..5edf7f6c0 100644 --- a/hugr-core/src/ops/custom.rs +++ b/hugr-core/src/ops/custom.rs @@ -14,7 +14,7 @@ use crate::extension::{ConstFoldResult, ExtensionId, ExtensionRegistry, OpDef, S use crate::hugr::internal::HugrMutInternals; use crate::hugr::{HugrView, NodeType}; use crate::types::type_param::TypeArg; -use crate::types::{EdgeKind, Signature}; +use crate::types::{EdgeKind, FunctionType}; use crate::{ops, Hugr, IncomingPort, Node}; use super::dataflow::DataflowOpTrait; @@ -132,7 +132,7 @@ impl DataflowOpTrait for CustomOp { } /// The signature of the operation. - fn signature(&self) -> Signature { + fn signature(&self) -> FunctionType { match self { Self::Opaque(op) => op.signature.clone(), Self::Extension(ext_op) => ext_op.signature(), @@ -181,7 +181,7 @@ pub struct ExtensionOp { )] def: Arc, args: Vec, - signature: Signature, // Cache + signature: FunctionType, // Cache } impl ExtensionOp { @@ -271,7 +271,7 @@ impl DataflowOpTrait for ExtensionOp { self.def().description() } - fn signature(&self) -> Signature { + fn signature(&self) -> FunctionType { self.signature.clone() } } @@ -286,7 +286,7 @@ pub struct OpaqueOp { #[cfg_attr(test, proptest(strategy = "any_nonempty_string()"))] description: String, // cache in advance so description() can return &str args: Vec, - signature: Signature, + signature: FunctionType, } fn qualify_name(res_id: &ExtensionId, op_name: &OpNameRef) -> OpName { @@ -300,7 +300,7 @@ impl OpaqueOp { op_name: impl Into, description: String, args: impl Into>, - signature: Signature, + signature: FunctionType, ) -> Self { Self { extension, @@ -342,7 +342,7 @@ impl DataflowOpTrait for OpaqueOp { &self.description } - fn signature(&self) -> Signature { + fn signature(&self) -> FunctionType { self.signature.clone() } } @@ -423,8 +423,8 @@ pub enum CustomOpError { SignatureMismatch { extension: ExtensionId, op: OpName, - stored: Signature, - computed: Signature, + stored: FunctionType, + computed: FunctionType, }, } @@ -436,7 +436,7 @@ mod test { #[test] fn new_opaque_op() { - let sig = Signature::new_endo(vec![QB_T]); + let sig = FunctionType::new_endo(vec![QB_T]); let op: CustomOp = OpaqueOp::new( "res".try_into().unwrap(), "op", diff --git a/hugr-core/src/ops/dataflow.rs b/hugr-core/src/ops/dataflow.rs index 41b6db807..e242f3eae 100644 --- a/hugr-core/src/ops/dataflow.rs +++ b/hugr-core/src/ops/dataflow.rs @@ -4,7 +4,7 @@ use super::{impl_op_name, OpTag, OpTrait}; use crate::extension::{ExtensionRegistry, ExtensionSet, SignatureError}; use crate::ops::StaticTag; -use crate::types::{EdgeKind, FunctionType, PolyFuncType, Signature, Type, TypeArg, TypeRow}; +use crate::types::{EdgeKind, FunctionType, PolyFuncType, Type, TypeArg, TypeRow}; use crate::IncomingPort; #[cfg(test)] @@ -13,7 +13,7 @@ use ::proptest_derive::Arbitrary; pub(crate) trait DataflowOpTrait { const TAG: OpTag; fn description(&self) -> &str; - fn signature(&self) -> Signature; + fn signature(&self) -> FunctionType; /// The edge kind for the non-dataflow or constant inputs of the operation, /// not described by the signature. @@ -99,7 +99,7 @@ impl DataflowOpTrait for Input { None } - fn signature(&self) -> Signature { + fn signature(&self) -> FunctionType { FunctionType::new(TypeRow::new(), self.types.clone()) } } @@ -111,8 +111,8 @@ impl DataflowOpTrait for Output { } // Note: We know what the input extensions should be, so we *could* give an - // instantiated Signature instead - fn signature(&self) -> Signature { + // instantiated FunctionType instead + fn signature(&self) -> FunctionType { FunctionType::new(self.types.clone(), TypeRow::new()) } @@ -128,7 +128,7 @@ impl OpTrait for T { fn tag(&self) -> OpTag { T::TAG } - fn dataflow_signature(&self) -> Option { + fn dataflow_signature(&self) -> Option { Some(DataflowOpTrait::signature(self)) } fn extension_delta(&self) -> ExtensionSet { @@ -158,10 +158,10 @@ impl StaticTag for T { #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[cfg_attr(test, derive(Arbitrary))] pub struct Call { - /// Signature of function being called + /// FunctionType of function being called func_sig: PolyFuncType, type_args: Vec, - instantiation: Signature, // Cache, so we can fail in try_new() not in signature() + instantiation: FunctionType, // Cache, so we can fail in try_new() not in signature() } impl_op_name!(Call); @@ -172,7 +172,7 @@ impl DataflowOpTrait for Call { "Call a function directly" } - fn signature(&self) -> Signature { + fn signature(&self) -> FunctionType { self.instantiation.clone() } @@ -252,8 +252,8 @@ impl Call { #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[cfg_attr(test, derive(Arbitrary))] pub struct CallIndirect { - /// Signature of function being called - pub signature: Signature, + /// FunctionType of function being called + pub signature: FunctionType, } impl_op_name!(CallIndirect); @@ -264,7 +264,7 @@ impl DataflowOpTrait for CallIndirect { "Call a function indirectly" } - fn signature(&self) -> Signature { + fn signature(&self) -> FunctionType { let mut s = self.signature.clone(); s.input .to_mut() @@ -288,7 +288,7 @@ impl DataflowOpTrait for LoadConstant { "Load a static constant in to the local dataflow graph" } - fn signature(&self) -> Signature { + fn signature(&self) -> FunctionType { FunctionType::new(TypeRow::new(), vec![self.datatype.clone()]) } @@ -328,10 +328,10 @@ impl LoadConstant { #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[cfg_attr(test, derive(Arbitrary))] pub struct LoadFunction { - /// Signature of the function + /// FunctionType of the function func_sig: PolyFuncType, type_args: Vec, - signature: Signature, // Cache, so we can fail in try_new() not in signature() + signature: FunctionType, // Cache, so we can fail in try_new() not in signature() } impl_op_name!(LoadFunction); impl DataflowOpTrait for LoadFunction { @@ -341,7 +341,7 @@ impl DataflowOpTrait for LoadFunction { "Load a static function in to the local dataflow graph" } - fn signature(&self) -> Signature { + fn signature(&self) -> FunctionType { self.signature.clone() } @@ -407,22 +407,22 @@ impl LoadFunction { /// Operations that is the parent of a dataflow graph. pub trait DataflowParent { - /// Signature of the inner dataflow graph. - fn inner_signature(&self) -> Signature; + /// FunctionType of the inner dataflow graph. + fn inner_signature(&self) -> FunctionType; } /// A simply nested dataflow graph. #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[cfg_attr(test, derive(Arbitrary))] pub struct DFG { - /// Signature of DFG node - pub signature: Signature, + /// FunctionType of DFG node + pub signature: FunctionType, } impl_op_name!(DFG); impl DataflowParent for DFG { - fn inner_signature(&self) -> Signature { + fn inner_signature(&self) -> FunctionType { self.signature.clone() } } @@ -434,7 +434,7 @@ impl DataflowOpTrait for DFG { "A simply nested dataflow graph" } - fn signature(&self) -> Signature { + fn signature(&self) -> FunctionType { self.inner_signature() } } diff --git a/hugr-core/src/ops/leaf.rs b/hugr-core/src/ops/leaf.rs index d2f43823a..f183e8a9d 100644 --- a/hugr-core/src/ops/leaf.rs +++ b/hugr-core/src/ops/leaf.rs @@ -5,7 +5,6 @@ use super::{impl_op_name, OpTag}; use crate::extension::ExtensionSet; -use crate::types::Signature; use crate::{ extension::ExtensionId, types::{EdgeKind, FunctionType, Type, TypeRow}, @@ -122,7 +121,7 @@ impl DataflowOpTrait for Noop { } /// The signature of the operation. - fn signature(&self) -> Signature { + fn signature(&self) -> FunctionType { FunctionType::new(vec![self.ty.clone()], vec![self.ty.clone()]) } @@ -144,7 +143,7 @@ impl DataflowOpTrait for MakeTuple { } /// The signature of the operation. - fn signature(&self) -> Signature { + fn signature(&self) -> FunctionType { FunctionType::new(self.tys.clone(), vec![Type::new_tuple(self.tys.clone().into_())]) } @@ -166,7 +165,7 @@ impl DataflowOpTrait for UnpackTuple { } /// The signature of the operation. - fn signature(&self) -> Signature { + fn signature(&self) -> FunctionType { FunctionType::new(vec![Type::new_tuple(self.tys.clone().into_())], self.tys.clone()) } @@ -188,7 +187,7 @@ impl DataflowOpTrait for Tag { } /// The signature of the operation. - fn signature(&self) -> Signature { + fn signature(&self) -> FunctionType { FunctionType::new( self.variants .get(self.tag) @@ -216,7 +215,7 @@ impl DataflowOpTrait for Lift { } /// The signature of the operation. - fn signature(&self) -> Signature { + fn signature(&self) -> FunctionType { FunctionType::new(self.type_row.clone(), self.type_row.clone()) .with_extension_delta(ExtensionSet::singleton(&self.new_extension)) } diff --git a/hugr-core/src/ops/module.rs b/hugr-core/src/ops/module.rs index c8f99c137..d16dc577b 100644 --- a/hugr-core/src/ops/module.rs +++ b/hugr-core/src/ops/module.rs @@ -7,7 +7,7 @@ use { ::proptest_derive::Arbitrary, }; -use crate::types::{EdgeKind, PolyFuncType, Signature}; +use crate::types::{EdgeKind, PolyFuncType, FunctionType}; use crate::types::{Type, TypeBound}; use super::dataflow::DataflowParent; @@ -44,7 +44,7 @@ pub struct FuncDefn { /// Name of function #[cfg_attr(test, proptest(strategy = "any_nonempty_string()"))] pub name: String, - /// Signature of the function + /// FunctionType of the function pub signature: PolyFuncType, } @@ -54,7 +54,7 @@ impl StaticTag for FuncDefn { } impl DataflowParent for FuncDefn { - fn inner_signature(&self) -> Signature { + fn inner_signature(&self) -> FunctionType { self.signature.body().clone() } } @@ -80,7 +80,7 @@ pub struct FuncDecl { /// Name of function #[cfg_attr(test, proptest(strategy = "any_nonempty_string()"))] pub name: String, - /// Signature of the function + /// FunctionType of the function pub signature: PolyFuncType, } diff --git a/hugr-core/src/std_extensions/arithmetic/conversions.rs b/hugr-core/src/std_extensions/arithmetic/conversions.rs index 5fd1c0392..a6a28ee63 100644 --- a/hugr-core/src/std_extensions/arithmetic/conversions.rs +++ b/hugr-core/src/std_extensions/arithmetic/conversions.rs @@ -3,7 +3,7 @@ use strum_macros::{EnumIter, EnumString, IntoStaticStr}; use crate::ops::OpName; -use crate::types::Type; +use crate::types::{FunTypeVarArgs, Type}; use crate::{ extension::{ prelude::sum_with_error, @@ -13,7 +13,7 @@ use crate::{ }, ops::{custom::ExtensionOp, NamedOp}, type_row, - types::{FunctionType, PolyFuncType, TypeArg}, + types::{PolyFuncType, TypeArg}, Extension, }; @@ -46,12 +46,12 @@ impl MakeOpDef for ConvertOpDef { vec![LOG_WIDTH_TYPE_PARAM], match self { trunc_s | trunc_u => - FunctionType::new( + FunTypeVarArgs::new( type_row![FLOAT64_TYPE].into_(), Type::::from(sum_with_error(int_tv(0))) ), convert_s | convert_u => - FunctionType::new(vec![int_tv(0)], type_row![FLOAT64_TYPE].into_()) + FunTypeVarArgs::new(vec![int_tv(0)], type_row![FLOAT64_TYPE].into_()) }).into() } diff --git a/hugr-core/src/std_extensions/arithmetic/int_ops.rs b/hugr-core/src/std_extensions/arithmetic/int_ops.rs index 07730a7b8..4a4b42345 100644 --- a/hugr-core/src/std_extensions/arithmetic/int_ops.rs +++ b/hugr-core/src/std_extensions/arithmetic/int_ops.rs @@ -10,7 +10,7 @@ use crate::ops::custom::ExtensionOp; use crate::ops::{NamedOp, OpName}; use crate::std_extensions::arithmetic::int_types::int_type; use crate::type_row; -use crate::types::{FunctionType, PolyFuncType}; +use crate::types::{FunTypeVarArgs, FunctionType, PolyFuncType}; use crate::utils::collect_array; use crate::{ @@ -161,7 +161,7 @@ impl MakeOpDef for IntOpDef { } itostring_u | itostring_s => PolyFuncType::new( vec![LOG_WIDTH_TYPE_PARAM], - FunctionType::new(vec![int_tv(0)], vec![STRING_TYPE]), + FunTypeVarArgs::new(vec![int_tv(0)], vec![STRING_TYPE]), ) .into(), } @@ -240,7 +240,7 @@ fn int_polytype( ) -> PolyFuncType { PolyFuncType::new( vec![LOG_WIDTH_TYPE_PARAM; n_vars], - FunctionType::new(input, output), + FunTypeVarArgs::new(input, output), ) } diff --git a/hugr-core/src/std_extensions/collections.rs b/hugr-core/src/std_extensions/collections.rs index 392417dff..3f7bda41a 100644 --- a/hugr-core/src/std_extensions/collections.rs +++ b/hugr-core/src/std_extensions/collections.rs @@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize}; use crate::ops::constant::ValueName; use crate::ops::{OpName, Value}; -use crate::types::TypeName; +use crate::types::{FunTypeVarArgs, TypeName}; use crate::{ extension::{ simple_op::{MakeExtensionOp, OpLoadError}, @@ -17,7 +17,7 @@ use crate::{ ops::{self, custom::ExtensionOp, NamedOp}, types::{ type_param::{TypeArg, TypeParam}, - CustomCheckFailure, CustomType, FunctionType, PolyFuncType, Type, TypeBound, + CustomCheckFailure, CustomType, PolyFuncType, Type, TypeBound, }, utils::sorted_consts, Extension, @@ -157,7 +157,7 @@ fn extension() -> Extension { "Pop from back of list".into(), PolyFuncType::new( vec![TP], - FunctionType::new(vec![l.clone()], vec![l.clone(), e.clone()]), + FunTypeVarArgs::new(vec![l.clone()], vec![l.clone(), e.clone()]), ), ) .unwrap() @@ -166,7 +166,7 @@ fn extension() -> Extension { .add_op( PUSH_NAME, "Push to back of list".into(), - PolyFuncType::new(vec![TP], FunctionType::new(vec![l.clone(), e], vec![l])), + PolyFuncType::new(vec![TP], FunTypeVarArgs::new(vec![l.clone(), e], vec![l])), ) .unwrap() .set_constant_folder(PushFold); diff --git a/hugr-core/src/std_extensions/logic.rs b/hugr-core/src/std_extensions/logic.rs index 2621b8f87..6c50c9794 100644 --- a/hugr-core/src/std_extensions/logic.rs +++ b/hugr-core/src/std_extensions/logic.rs @@ -5,7 +5,7 @@ use strum_macros::{EnumIter, EnumString, IntoStaticStr}; use crate::extension::{ConstFold, ConstFoldResult}; use crate::ops::constant::ValueName; use crate::ops::{OpName, Value}; -use crate::types::FunctionType; +use crate::types::{FunTypeVarArgs, FunctionType}; use crate::{ extension::{ prelude::BOOL_T, @@ -160,7 +160,7 @@ fn logic_op_sig() -> impl SignatureFromArgs { return Err(SignatureError::InvalidTypeArgs); }; let var_arg_row = vec![BOOL_T; n as usize]; - Ok(FunctionType::new(var_arg_row, vec![BOOL_T]).into()) + Ok(FunTypeVarArgs::new(var_arg_row, vec![BOOL_T]).into()) } fn static_params(&self) -> &[TypeParam] { diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index a483960f3..7babdf7b8 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -16,7 +16,7 @@ use crate::utils::display_list_with_separator; pub use check::SumTypeError; pub use custom::CustomType; pub use poly_func::PolyFuncType; -pub use signature::{FunctionType, Signature}; +pub use signature::{FunctionType, FunTypeVarArgs}; use smol_str::SmolStr; pub use type_param::TypeArg; pub use type_row::TypeRow; @@ -217,7 +217,7 @@ pub enum TypeEnum { test, proptest(strategy = "any_with::(params).prop_map(Box::new)") )] - Box, + Box, ), // Index into TypeParams, and cache of TypeBound (checked in validation) #[allow(missing_docs)] @@ -298,7 +298,7 @@ impl Type { const EMPTY_TYPEROW_REF: &'static TypeRow = &Self::EMPTY_TYPEROW; /// Initialize a new function type. - pub fn new_function(fun_ty: impl Into) -> Self { + pub fn new_function(fun_ty: impl Into) -> Self { Self::new(TypeEnum::Function(Box::new(fun_ty.into()))) } diff --git a/hugr-core/src/types/serialize.rs b/hugr-core/src/types/serialize.rs index d2f11277c..14f6f53c9 100644 --- a/hugr-core/src/types/serialize.rs +++ b/hugr-core/src/types/serialize.rs @@ -1,4 +1,4 @@ -use super::{FunctionType, SumType, Type, TypeArg, TypeBound, TypeEnum}; +use super::{FunTypeVarArgs, SumType, Type, TypeArg, TypeBound, TypeEnum}; use super::custom::CustomType; @@ -11,7 +11,7 @@ use crate::ops::AliasDecl; pub(super) enum SerSimpleType { Q, I, - G(Box), + G(Box), Sum(SumType), Array { inner: Box, len: u64 }, Opaque(CustomType), diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index e7146e139..c945b0b7a 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -1,4 +1,4 @@ -//! Abstract and concrete Signature types. +//! Abstract and concrete FunctionType types. use itertools::Either; @@ -36,9 +36,11 @@ pub struct FuncTypeBase { /// The concept of "signature" in the spec - the edges required to/from a node or graph /// and also the target (value) of a call (static). -pub type Signature = FuncTypeBase; +pub type FunctionType = FuncTypeBase; -pub type FunctionType = FuncTypeBase; +/// A function of potentially-unknown arity; passable as a value round a Hugr +/// (see [Type::new_function]) but not a valid node type. +pub type FunTypeVarArgs = FuncTypeBase; impl FuncTypeBase { /// Builder method, add extension_reqs to an FunctionType @@ -98,7 +100,7 @@ impl FuncTypeBase { } } -impl FunctionType { +impl FunTypeVarArgs { /// If this FunctionType contains any row variables, return one. pub fn find_rowvar(&self) -> Option<(usize, TypeBound)> { self.input @@ -111,9 +113,9 @@ impl FunctionType { } } -impl Signature { - pub(crate) fn into_(self) -> FunctionType { - FunctionType { +impl FunctionType { + pub(crate) fn into_(self) -> FunTypeVarArgs { + FunTypeVarArgs { input: self.input.into_(), output: self.output.into_(), extension_reqs: self.extension_reqs @@ -246,18 +248,18 @@ impl Display for FuncTypeBase { } } -impl TryFrom for Signature { +impl TryFrom for FunctionType { type Error = SignatureError; - fn try_from(value: FunctionType) -> Result { + fn try_from(value: FunTypeVarArgs) -> Result { let input: TypeRow = value.input.try_into()?; let output: TypeRow = value.output.try_into()?; Ok(Self::new(input, output).with_extension_delta(value.extension_reqs)) } } -impl PartialEq for Signature { - fn eq(&self, other: &FunctionType) -> bool { +impl PartialEq for FunctionType { + fn eq(&self, other: &FunTypeVarArgs) -> bool { self.input == other.input && self.output == other.output && self.extension_reqs == other.extension_reqs diff --git a/hugr-py/src/hugr/serialization/tys.py b/hugr-py/src/hugr/serialization/tys.py index f19e27340..fde79244e 100644 --- a/hugr-py/src/hugr/serialization/tys.py +++ b/hugr-py/src/hugr/serialization/tys.py @@ -353,11 +353,11 @@ class Type(RootModel): # ------------------------------------------- -# --------------- Signature ----------------- +# --------------- FunctionType ----------------- # ------------------------------------------- -class Signature(ConfiguredBaseModel): +class FunctionType(ConfiguredBaseModel): """Describes the edges required to/from a node. This includes both the concept of "signature" in the spec, and also the target From 695ce291a070b71ded16935c41c6cd56bf5c32a3 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 11 Jun 2024 10:51:07 +0100 Subject: [PATCH 052/115] Reinstate conversion in PFT::new, FunctionType --Into-> FunTypeVarArgs --- hugr-core/src/types/poly_func.rs | 4 ++-- hugr-core/src/types/signature.rs | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index 96a11e525..fff376ec0 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -83,10 +83,10 @@ impl PolyFuncType { /// Create a new PolyFuncType given the kinds of the variables it declares /// and the underlying function type. - pub fn new(params: impl Into>, body: FuncTypeBase) -> Self { + pub fn new(params: impl Into>, body: impl Into>) -> Self { Self { params: params.into(), - body + body: body.into() } } diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index c945b0b7a..8965377b2 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -258,6 +258,16 @@ impl TryFrom for FunctionType { } } +impl From for FunTypeVarArgs { + fn from(value: FunctionType) -> Self { + Self { + input: value.input.into_(), + output: value.output.into_(), + extension_reqs: value.extension_reqs + } + } +} + impl PartialEq for FunctionType { fn eq(&self, other: &FunTypeVarArgs) -> bool { self.input == other.input From ddbfbdd0c71faabd379c56a50473f27947a79455 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 11 Jun 2024 13:52:03 +0100 Subject: [PATCH 053/115] Change some Fun{ctionType->TypeVarArgs}::new --- hugr-core/src/builder/dataflow.rs | 4 +- hugr-core/src/hugr/serialize/test.rs | 12 ++--- hugr-core/src/hugr/validate/test.rs | 79 ++++------------------------ hugr-core/src/types/poly_func.rs | 4 +- 4 files changed, 20 insertions(+), 79 deletions(-) diff --git a/hugr-core/src/builder/dataflow.rs b/hugr-core/src/builder/dataflow.rs index 626227ce5..7dc4886a6 100644 --- a/hugr-core/src/builder/dataflow.rs +++ b/hugr-core/src/builder/dataflow.rs @@ -218,7 +218,7 @@ pub(crate) mod test { use crate::std_extensions::logic::test::and_op; use crate::types::type_param::TypeParam; - use crate::types::{FunctionType, Type, TypeBound}; + use crate::types::{FunTypeVarArgs, FunctionType, Type, TypeBound}; use crate::utils::test_quantum_extension::h_gate; use crate::{ builder::test::{n_identity, BIT, NAT, QB}, @@ -564,7 +564,7 @@ pub(crate) mod test { PolyFuncType::new( [TypeParam::new_list(TypeBound::Copyable)], FunctionType::new( - Type::new_function(FunctionType::new(Type::::from(USIZE_T), tv.clone())), + Type::new_function(FunTypeVarArgs::new(USIZE_T, tv.clone())), vec![], ), ), diff --git a/hugr-core/src/hugr/serialize/test.rs b/hugr-core/src/hugr/serialize/test.rs index 8a591c3d2..837e56d11 100644 --- a/hugr-core/src/hugr/serialize/test.rs +++ b/hugr-core/src/hugr/serialize/test.rs @@ -14,7 +14,7 @@ use crate::std_extensions::arithmetic::int_ops::INT_OPS_REGISTRY; use crate::std_extensions::arithmetic::int_types::{int_custom_type, ConstInt, INT_TYPES}; use crate::std_extensions::logic::NotOp; use crate::types::{ - type_param::TypeParam, FunctionType, PolyFuncType, SumType, Type, TypeArg, TypeBound, + type_param::TypeParam, FunctionType, FunTypeVarArgs, PolyFuncType, SumType, Type, TypeArg, TypeBound, }; use crate::{type_row, OutgoingPort}; @@ -445,10 +445,10 @@ fn polyfunctype2() -> PolyFuncType { let tv1 = Type::new_row_var_use(1, TypeBound::Eq); let params = [TypeBound::Any, TypeBound::Eq].map(TypeParam::new_list); let inputs = vec![ - Type::new_function(FunctionType::new(tv0.clone(), tv1.clone())), + Type::new_function(FunTypeVarArgs::new(tv0.clone(), tv1.clone())), tv0, ]; - let res = PolyFuncType::new(params, FunctionType::new(inputs, tv1)); + let res = PolyFuncType::new(params, FunTypeVarArgs::new(inputs, tv1)); // Just check we've got the arguments the right way round // (not that it really matters for the serialization schema we have) res.validate(&EMPTY_REG).unwrap(); @@ -465,21 +465,19 @@ fn polyfunctype2() -> PolyFuncType { #[case(PolyFuncType::new( [TypeParam::new_list(TypeBound::Any)], FunctionType::new_endo(Type::new_tuple(Type::new_row_var_use(0, TypeBound::Any)))))] -#[case(polyfunctype2())] fn roundtrip_polyfunctype_fixedlen(#[case] poly_func_type: PolyFuncType) { check_testing_roundtrip(poly_func_type) } #[rstest] -#[case(FunctionType::new_endo(type_row![]).into())] -#[case(polyfunctype1())] +#[case(FunTypeVarArgs::new_endo(type_row![]).into())] #[case(PolyFuncType::new([TypeParam::Opaque { ty: int_custom_type(TypeArg::BoundedNat { n: 1 }) }], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Copyable)])))] #[case(PolyFuncType::new([TypeBound::Eq.into()], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Eq)])))] #[case(PolyFuncType::new([TypeParam::new_list(TypeBound::Any)], FunctionType::new_endo(type_row![])))] #[case(PolyFuncType::new([TypeParam::Tuple { params: [TypeBound::Any.into(), TypeParam::bounded_nat(2.try_into().unwrap())].into() }], FunctionType::new_endo(type_row![])))] #[case(PolyFuncType::new( [TypeParam::new_list(TypeBound::Any)], - FunctionType::new_endo(Type::new_row_var_use(0, TypeBound::Any))))] + FunTypeVarArgs::new_endo(Type::new_row_var_use(0, TypeBound::Any))))] #[case(polyfunctype2())] fn roundtrip_polyfunctype_varlen(#[case] poly_func_type: PolyFuncType) { check_testing_roundtrip(poly_func_type) diff --git a/hugr-core/src/hugr/validate/test.rs b/hugr-core/src/hugr/validate/test.rs index 8e8e1f0c5..f20ea9f2b 100644 --- a/hugr-core/src/hugr/validate/test.rs +++ b/hugr-core/src/hugr/validate/test.rs @@ -18,7 +18,7 @@ use crate::ops::{self, Noop, OpType, Value}; use crate::std_extensions::logic::test::{and_op, or_op}; use crate::std_extensions::logic::{self, NotOp}; use crate::types::type_param::{TypeArg, TypeArgError}; -use crate::types::{CustomType, FunctionType, PolyFuncType, Type, TypeBound, TypeRow}; +use crate::types::{CustomType, FunTypeVarArgs, FunctionType, PolyFuncType, Type, TypeBound, TypeRow}; use crate::{const_extension_ids, type_row, Direction, IncomingPort, Node}; const NAT: Type = crate::extension::prelude::USIZE_T; @@ -586,10 +586,10 @@ pub(crate) fn extension_with_eval_parallel() -> Extension { let inputs = Type::new_row_var_use(0, TypeBound::Any); let outputs = Type::new_row_var_use(1, TypeBound::Any); - let evaled_fn = Type::new_function(FunctionType::new(inputs.clone(), outputs.clone())); + let evaled_fn = Type::new_function(FunTypeVarArgs::new(inputs.clone(), outputs.clone())); let pf = PolyFuncType::new( [rowp.clone(), rowp.clone()], - FunctionType::new(vec![evaled_fn, inputs], outputs), + FunTypeVarArgs::new(vec![evaled_fn, inputs], outputs), ); e.add_op("eval".into(), "".into(), pf).unwrap(); @@ -598,10 +598,10 @@ pub(crate) fn extension_with_eval_parallel() -> Extension { [rowp.clone(), rowp.clone(), rowp.clone(), rowp.clone()], FunctionType::new( vec![ - Type::new_function(FunctionType::new(rv(0), rv(2))), - Type::new_function(FunctionType::new(rv(1), rv(3))), + Type::new_function(FunTypeVarArgs::new(rv(0), rv(2))), + Type::new_function(FunTypeVarArgs::new(rv(1), rv(3))), ], - Type::new_function(FunctionType::new(vec![rv(0), rv(1)], vec![rv(2), rv(3)])), + Type::new_function(FunTypeVarArgs::new(vec![rv(0), rv(1)], vec![rv(2), rv(3)])), ), ); e.add_op("parallel".into(), "".into(), pf).unwrap(); @@ -641,18 +641,18 @@ fn instantiate_row_variables() -> Result<(), Box> { Ok(()) } -fn seq1ty(t: Type) -> TypeArg { +fn seq1ty(t: Type) -> TypeArg { TypeArg::Sequence { elems: vec![t.into()], } } #[test] -fn inner_row_variables() -> Result<(), Box> { +fn row_variables() -> Result<(), Box> { let e = extension_with_eval_parallel(); let tv = Type::new_row_var_use(0, TypeBound::Any); - let inner_ft = Type::new_function(FunctionType::new_endo(tv.clone())); - let ft_usz = Type::new_function(FunctionType::new_endo(vec![tv.clone(), USIZE_T])); + let inner_ft = Type::new_function(FunTypeVarArgs::new_endo(tv.clone())); + let ft_usz = Type::new_function(FunTypeVarArgs::new_endo(vec![tv.clone(), USIZE_T.into()])); let mut fb = FunctionBuilder::new( "id", PolyFuncType::new( @@ -676,7 +676,7 @@ fn inner_row_variables() -> Result<(), Box> { }; let par = e.instantiate_extension_op( "parallel", - [tv.clone(), USIZE_T, tv.clone(), USIZE_T].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])?; @@ -687,63 +687,6 @@ fn inner_row_variables() -> Result<(), Box> { Ok(()) } -#[rstest] -#[case(false)] -#[case(true)] -fn no_outer_row_variables(#[case] connect: bool) -> Result<(), Box> { - let e = extension_with_eval_parallel(); - let tv = Type::new_row_var_use(0, TypeBound::Copyable); - let fun_ty = Type::new_function(FunctionType::new(USIZE_T, tv.clone())); - let results = if connect { vec![tv.clone()] } else { vec![] }; - let mut fb = Hugr::new( - FuncDefn { - name: "bad_eval".to_string(), - signature: PolyFuncType::new( - [TypeParam::new_list(TypeBound::Copyable)], - FunctionType::new(fun_ty.clone(), results.clone()), - ), - } - .into(), - ); - let inp = fb.add_node_with_parent( - fb.root(), - ops::Input { - types: fun_ty.into(), - }, - ); - let out = fb.add_node_with_parent( - fb.root(), - ops::Output { - types: results.into(), - }, - ); - let cst = fb.add_node_with_parent( - fb.root(), - ops::Const::new(crate::extension::prelude::ConstUsize::new(5).into()), - ); - let i = fb.add_node_with_parent(fb.root(), ops::LoadConstant { datatype: USIZE_T }); - fb.connect(cst, 0, i, 0); - - let ev = fb.add_node_with_parent( - fb.root(), - e.instantiate_extension_op("eval", [seq1ty(USIZE_T), seq1ty(tv)], &PRELUDE_REGISTRY)?, - ); - fb.connect(inp, 0, ev, 0); - fb.connect(i, 0, ev, 1); - if connect { - fb.connect(ev, 0, out, 0); - } - let reg = ExtensionRegistry::try_new([PRELUDE.to_owned(), e]).unwrap(); - assert_matches!( - fb.validate(®).unwrap_err(), - ValidationError::SignatureError { - node, - cause: SignatureError::RowVarWhereTypeExpected { idx: 0 } - } => assert!([ev, out].contains(&node)) - ); - Ok(()) -} - #[test] fn test_polymorphic_call() -> Result<(), Box> { let mut e = Extension::new(EXT_ID); diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index fff376ec0..f7faa1e76 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -429,10 +429,10 @@ pub(crate) mod test { #[test] fn row_variables_inner() { - let inner_fty = Type::new_function(FunctionType::new_endo(vec![Type::new_row_var_use( + let inner_fty = Type::new_function(FunTypeVarArgs::new_endo(Type::new_row_var_use( 0, TypeBound::Copyable, - )])); + ))); let pf = PolyFuncType::new_validated( [TypeParam::List { param: Box::new(TypeParam::Type { From b36001f26b5b66cc3dfb188f143195a7435f6ab7 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 11 Jun 2024 13:57:16 +0100 Subject: [PATCH 054/115] FuncTypeBase double-RV PartialEq; PolyFuncType generic new_validated --- hugr-core/src/types/poly_func.rs | 11 ++++++----- hugr-core/src/types/signature.rs | 6 +++--- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index f7faa1e76..cc543c80f 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -131,8 +131,9 @@ pub(crate) mod test { PRELUDE_REGISTRY, }; use crate::std_extensions::collections::{EXTENSION, LIST_TYPENAME}; + use crate::types::signature::FuncTypeBase; use crate::types::type_param::{TypeArg, TypeArgError, TypeParam}; - use crate::types::{CustomType, FunctionType, Type, TypeBound, TypeName}; + use crate::types::{CustomType, FunTypeVarArgs, FunctionType, Type, TypeBound, TypeName}; use crate::Extension; use super::PolyFuncType; @@ -142,10 +143,10 @@ pub(crate) mod test { ExtensionRegistry::try_new([PRELUDE.to_owned(), EXTENSION.to_owned()]).unwrap(); } - impl PolyFuncType { + impl PolyFuncType { fn new_validated( params: impl Into>, - body: FunctionType, + body: FuncTypeBase, extension_registry: &ExtensionRegistry, ) -> Result { let res = Self::new(params, body); @@ -368,7 +369,7 @@ pub(crate) mod test { }; let e = PolyFuncType::new_validated( [decl.clone()], - FunctionType::new( + FunTypeVarArgs::new( vec![USIZE_T], vec![Type::new_row_var_use(0, TypeBound::Copyable)], ), @@ -397,7 +398,7 @@ pub(crate) mod test { let rty = Type::new_row_var_use(0, TypeBound::Any); let pf = PolyFuncType::new_validated( [TypeParam::new_list(TP_ANY)], - FunctionType::new(vec![USIZE_T, rty.clone()], vec![Type::new_tuple(rty)]), + FunTypeVarArgs::new(vec![USIZE_T.into(), rty.clone()], vec![Type::new_tuple(rty)]), &PRELUDE_REGISTRY, ) .unwrap(); diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index 8965377b2..cdcd44b49 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -14,7 +14,7 @@ use crate::{Direction, IncomingPort, OutgoingPort, Port}; #[cfg(test)] use {crate::proptest::RecursionDepth, ::proptest::prelude::*, proptest_derive::Arbitrary}; -#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug, Default, Eq, serde::Serialize, serde::Deserialize)] #[cfg_attr(test, derive(Arbitrary), proptest(params = "RecursionDepth"))] /// Describes the edges required to/from a node (when ROWVARS=false); /// or (when ROWVARS=true) the type of a [Graph] or the inputs/outputs from an OpDef @@ -268,8 +268,8 @@ impl From for FunTypeVarArgs { } } -impl PartialEq for FunctionType { - fn eq(&self, other: &FunTypeVarArgs) -> bool { +impl PartialEq> for FuncTypeBase { + fn eq(&self, other: &FuncTypeBase) -> bool { self.input == other.input && self.output == other.output && self.extension_reqs == other.extension_reqs From 543806512a80e639e4ea58db5707446d0950d2bf Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 11 Jun 2024 14:16:00 +0100 Subject: [PATCH 055/115] Add could-be-anything annotations --- hugr-core/src/extension/prelude.rs | 2 +- hugr-core/src/extension/type_def.rs | 4 ++-- hugr-core/src/hugr/serialize/test.rs | 6 +++--- hugr-core/src/ops/constant.rs | 6 +++--- hugr-core/src/types.rs | 4 ++-- hugr-core/src/types/poly_func.rs | 2 +- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/hugr-core/src/extension/prelude.rs b/hugr-core/src/extension/prelude.rs index a20201250..7853ec2f4 100644 --- a/hugr-core/src/extension/prelude.rs +++ b/hugr-core/src/extension/prelude.rs @@ -380,7 +380,7 @@ mod test { .instantiate([]) .unwrap(); - let ext_type = Type::new_extension(ext_def); + let ext_type: Type = Type::new_extension(ext_def); assert_eq!(ext_type, ERROR_TYPE); let error_val = ConstError::new(2, "my message"); diff --git a/hugr-core/src/extension/type_def.rs b/hugr-core/src/extension/type_def.rs index 5ca9e2f7c..8933baa57 100644 --- a/hugr-core/src/extension/type_def.rs +++ b/hugr-core/src/extension/type_def.rs @@ -182,14 +182,14 @@ mod test { description: "Some parametrised type".into(), bound: TypeDefBound::FromParams(vec![0]), }; - let typ = Type::new_extension( + let typ: Type = Type::new_extension( def.instantiate(vec![TypeArg::Type { ty: Type::new_function(FunctionType::new(vec![], vec![])), }]) .unwrap(), ); assert_eq!(typ.least_upper_bound(), TypeBound::Copyable); - let typ2 = Type::new_extension(def.instantiate([TypeArg::Type { ty: USIZE_T }]).unwrap()); + let typ2: Type = Type::new_extension(def.instantiate([TypeArg::Type { ty: USIZE_T }]).unwrap()); assert_eq!(typ2.least_upper_bound(), TypeBound::Eq); // And some bad arguments...firstly, wrong kind of TypeArg: diff --git a/hugr-core/src/hugr/serialize/test.rs b/hugr-core/src/hugr/serialize/test.rs index 837e56d11..d86ee810f 100644 --- a/hugr-core/src/hugr/serialize/test.rs +++ b/hugr-core/src/hugr/serialize/test.rs @@ -390,14 +390,14 @@ fn serialize_types_roundtrip() { check_testing_roundtrip(g.clone()); // A Simple tuple - let t = Type::new_tuple(vec![USIZE_T.into(), g]); + let t: Type = Type::new_tuple(vec![USIZE_T.into(), g]); check_testing_roundtrip(t); // A Classic sum - let t = Type::new_sum([type_row![USIZE_T], type_row![FLOAT64_TYPE]]); + let t: Type = Type::new_sum([type_row![USIZE_T], type_row![FLOAT64_TYPE]]); check_testing_roundtrip(t); - let t = Type::new_unit_sum(4); + let t: Type = Type::new_unit_sum(4); check_testing_roundtrip(t); } diff --git a/hugr-core/src/ops/constant.rs b/hugr-core/src/ops/constant.rs index 1942d8a3f..c338f1a1d 100644 --- a/hugr-core/src/ops/constant.rs +++ b/hugr-core/src/ops/constant.rs @@ -565,7 +565,7 @@ mod test { fn function_value(simple_dfg_hugr: Hugr) { let v = Value::function(simple_dfg_hugr).unwrap(); - let correct_type = Type::new_function(FunctionType::new_endo(type_row![ + let correct_type: Type = Type::new_function(FunctionType::new_endo(type_row![ crate::extension::prelude::BOOL_T ])); @@ -624,12 +624,12 @@ mod test { let yaml_const: Value = CustomSerialized::new(typ_int.clone(), YamlValue::Number(6.into()), ex_id.clone()) .into(); - let classic_t = Type::new_extension(typ_int.clone()); + let classic_t: Type = Type::new_extension(typ_int.clone()); assert_matches!(classic_t.least_upper_bound(), TypeBound::Eq); assert_eq!(yaml_const.get_type(), classic_t); let typ_qb = CustomType::new("my_type", vec![], ex_id, TypeBound::Eq); - let t = Type::new_extension(typ_qb.clone()); + let t: Type = Type::new_extension(typ_qb.clone()); assert_ne!(yaml_const.get_type(), t); } diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index 7babdf7b8..ad4c13115 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -602,8 +602,8 @@ pub(crate) mod test { #[rstest::rstest] fn sum_construct() { - let pred1 = Type::new_sum([Type::EMPTY_TYPEROW, Type::EMPTY_TYPEROW]); - let pred2 = Type::new_unit_sum(2); + let pred1: Type = Type::new_sum([Type::EMPTY_TYPEROW, Type::EMPTY_TYPEROW]); + let pred2: Type = Type::new_unit_sum(2); assert_eq!(pred1, pred2); diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index cc543c80f..8bdd78533 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -398,7 +398,7 @@ pub(crate) mod test { let rty = Type::new_row_var_use(0, TypeBound::Any); let pf = PolyFuncType::new_validated( [TypeParam::new_list(TP_ANY)], - FunTypeVarArgs::new(vec![USIZE_T.into(), rty.clone()], vec![Type::new_tuple(rty)]), + FunTypeVarArgs::new(vec![USIZE_T.into(), rty.clone()], vec![Type::::new_tuple(rty)]), &PRELUDE_REGISTRY, ) .unwrap(); From 279fdae9dd9e17e6ac4aaf233d339eccd6a62fc1 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 11 Jun 2024 14:21:49 +0100 Subject: [PATCH 056/115] fix tests in type_param.rs --- hugr-core/src/types/type_param.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hugr-core/src/types/type_param.rs b/hugr-core/src/types/type_param.rs index 7e1dfda59..e89501079 100644 --- a/hugr-core/src/types/type_param.rs +++ b/hugr-core/src/types/type_param.rs @@ -485,13 +485,13 @@ mod test { check(vec![], &seq_param).unwrap(); check_seq(&[rowvar(0, TypeBound::Eq)], &seq_param).unwrap(); check_seq( - &[rowvar(1, TypeBound::Any), USIZE_T, rowvar(0, TypeBound::Eq)], + &[rowvar(1, TypeBound::Any), USIZE_T.into(), rowvar(0, TypeBound::Eq)], &TypeParam::new_list(TypeBound::Any), ) .unwrap(); // Next one fails because a list of Eq is required check_seq( - &[rowvar(1, TypeBound::Any), USIZE_T, rowvar(0, TypeBound::Eq)], + &[rowvar(1, TypeBound::Any), USIZE_T.into(), rowvar(0, TypeBound::Eq)], &seq_param, ) .unwrap_err(); From d2204674a9bf61ca79d2886e9f454a9b5a2a6115 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 11 Jun 2024 14:22:05 +0100 Subject: [PATCH 057/115] fix tests constructing PolyFuncType...return to this --- hugr-core/src/utils.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/hugr-core/src/utils.rs b/hugr-core/src/utils.rs index 863cfa7a9..5c8172729 100644 --- a/hugr-core/src/utils.rs +++ b/hugr-core/src/utils.rs @@ -118,11 +118,12 @@ pub(crate) mod test_quantum_extension { use lazy_static::lazy_static; fn one_qb_func() -> PolyFuncType { - FunctionType::new_endo(type_row![QB_T]).into() + PolyFuncType::new(vec![], FunctionType::new_endo(QB_T)) } fn two_qb_func() -> PolyFuncType { - FunctionType::new_endo(type_row![QB_T, QB_T]).into() + // ALAN this and prev would be easier with TypeRow -> TypeRow + PolyFuncType::new(vec![], FunctionType::new_endo(type_row![QB_T, QB_T])) } /// The extension identifier. pub const EXTENSION_ID: ExtensionId = ExtensionId::new_unchecked("test.quantum"); From 4a3d643ae6d0ce2838d2ec5ff4ac13b6c5673d80 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 11 Jun 2024 14:26:13 +0100 Subject: [PATCH 058/115] Generalize new_sum like SumType::new. Fixes all but 4, really? --- hugr-core/src/types.rs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index ad4c13115..3ea350a3e 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -314,12 +314,7 @@ impl Type { /// Initialize a new sum type by providing the possible variant types. #[inline(always)] - pub fn new_sum(variants: impl IntoIterator>) -> Self where - { - let variants: Vec>> = variants - .into_iter() - .map(|t| t.into_owned().into_iter().map(Type::into_).collect()) - .collect(); + pub fn new_sum(variants: impl IntoIterator) -> Self where R: Into> { Self::new(TypeEnum::Sum(SumType::new(variants))) } From 79679ca1dbeba81f6d96e25d97fae9c3e0ca07ce Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 11 Jun 2024 14:29:31 +0100 Subject: [PATCH 059/115] Fix the 4 errors with into_; now we get 26, and maybe don't want to use into_ --- hugr-core/src/ops/controlflow.rs | 6 +++--- hugr-core/src/ops/leaf.rs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/hugr-core/src/ops/controlflow.rs b/hugr-core/src/ops/controlflow.rs index f4f8024f4..bd1cc5ced 100644 --- a/hugr-core/src/ops/controlflow.rs +++ b/hugr-core/src/ops/controlflow.rs @@ -39,7 +39,7 @@ impl DataflowOpTrait for TailLoop { impl TailLoop { /// Build the output TypeRow of the child graph of a TailLoop node. pub(crate) fn body_output_row(&self) -> TypeRow { - let sum_type = Type::new_sum([self.just_inputs.clone(), self.just_outputs.clone()]); + let sum_type = Type::new_sum([self.just_inputs.clone().into_(), self.just_outputs.clone().into_()]); let mut outputs = vec![sum_type]; outputs.extend_from_slice(&self.rest); outputs.into() @@ -77,7 +77,7 @@ impl DataflowOpTrait for Conditional { let mut inputs = self.other_inputs.clone(); inputs .to_mut() - .insert(0, Type::new_sum(self.sum_rows.iter().cloned())); + .insert(0, Type::new_sum(self.sum_rows.iter().cloned().map(TypeRow::into_))); FunctionType::new(inputs, self.outputs.clone()) .with_extension_delta(self.extension_delta.clone()) } @@ -155,7 +155,7 @@ impl StaticTag for ExitBlock { impl DataflowParent for DataflowBlock { fn inner_signature(&self) -> FunctionType { // The node outputs a Sum before the data outputs of the block node - let sum_type = Type::new_sum(self.sum_rows.iter().cloned()); + let sum_type = Type::new_sum(self.sum_rows.iter().cloned().map(TypeRow::into_)); let mut node_outputs = vec![sum_type]; node_outputs.extend_from_slice(&self.other_outputs); FunctionType::new(self.inputs.clone(), TypeRow::from(node_outputs)) diff --git a/hugr-core/src/ops/leaf.rs b/hugr-core/src/ops/leaf.rs index f183e8a9d..66e166af4 100644 --- a/hugr-core/src/ops/leaf.rs +++ b/hugr-core/src/ops/leaf.rs @@ -193,7 +193,7 @@ impl DataflowOpTrait for Tag { .get(self.tag) .expect("Not a valid tag") .clone(), - vec![Type::new_sum(self.variants.clone())], + vec![Type::new_sum(self.variants.iter().cloned().map(TypeRow::into_))], ) } From ffd0cf74f953497cb9fa4bbf7112511041dadf58 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 11 Jun 2024 14:32:54 +0100 Subject: [PATCH 060/115] Revert "Fix the 4 errors with into_; now we get 26, and maybe don't want to use into_" This reverts commit 79679ca1dbeba81f6d96e25d97fae9c3e0ca07ce. --- hugr-core/src/ops/controlflow.rs | 6 +++--- hugr-core/src/ops/leaf.rs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/hugr-core/src/ops/controlflow.rs b/hugr-core/src/ops/controlflow.rs index bd1cc5ced..f4f8024f4 100644 --- a/hugr-core/src/ops/controlflow.rs +++ b/hugr-core/src/ops/controlflow.rs @@ -39,7 +39,7 @@ impl DataflowOpTrait for TailLoop { impl TailLoop { /// Build the output TypeRow of the child graph of a TailLoop node. pub(crate) fn body_output_row(&self) -> TypeRow { - let sum_type = Type::new_sum([self.just_inputs.clone().into_(), self.just_outputs.clone().into_()]); + let sum_type = Type::new_sum([self.just_inputs.clone(), self.just_outputs.clone()]); let mut outputs = vec![sum_type]; outputs.extend_from_slice(&self.rest); outputs.into() @@ -77,7 +77,7 @@ impl DataflowOpTrait for Conditional { let mut inputs = self.other_inputs.clone(); inputs .to_mut() - .insert(0, Type::new_sum(self.sum_rows.iter().cloned().map(TypeRow::into_))); + .insert(0, Type::new_sum(self.sum_rows.iter().cloned())); FunctionType::new(inputs, self.outputs.clone()) .with_extension_delta(self.extension_delta.clone()) } @@ -155,7 +155,7 @@ impl StaticTag for ExitBlock { impl DataflowParent for DataflowBlock { fn inner_signature(&self) -> FunctionType { // The node outputs a Sum before the data outputs of the block node - let sum_type = Type::new_sum(self.sum_rows.iter().cloned().map(TypeRow::into_)); + let sum_type = Type::new_sum(self.sum_rows.iter().cloned()); let mut node_outputs = vec![sum_type]; node_outputs.extend_from_slice(&self.other_outputs); FunctionType::new(self.inputs.clone(), TypeRow::from(node_outputs)) diff --git a/hugr-core/src/ops/leaf.rs b/hugr-core/src/ops/leaf.rs index 66e166af4..f183e8a9d 100644 --- a/hugr-core/src/ops/leaf.rs +++ b/hugr-core/src/ops/leaf.rs @@ -193,7 +193,7 @@ impl DataflowOpTrait for Tag { .get(self.tag) .expect("Not a valid tag") .clone(), - vec![Type::new_sum(self.variants.iter().cloned().map(TypeRow::into_))], + vec![Type::new_sum(self.variants.clone())], ) } From 7ddb6bfe0d543f15f7743b26e27208cf923e953a Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 11 Jun 2024 14:46:22 +0100 Subject: [PATCH 061/115] Add TypeRow --Into-> TypeRow, fix missing-type-annots by skipping .into(_)() --- hugr-core/src/extension/infer/test.rs | 4 ++-- hugr-core/src/hugr/serialize/test.rs | 2 +- hugr-core/src/ops/leaf.rs | 4 ++-- .../src/std_extensions/arithmetic/conversions.rs | 4 ++-- hugr-core/src/std_extensions/arithmetic/int_ops.rs | 6 +++--- hugr-core/src/types.rs | 11 ++++++----- hugr-core/src/types/type_param.rs | 8 ++++++-- hugr-core/src/types/type_row.rs | 7 +++++++ hugr-passes/src/const_fold.rs | 2 +- 9 files changed, 30 insertions(+), 18 deletions(-) diff --git a/hugr-core/src/extension/infer/test.rs b/hugr-core/src/extension/infer/test.rs index 73ef8289d..8cec0a76c 100644 --- a/hugr-core/src/extension/infer/test.rs +++ b/hugr-core/src/extension/infer/test.rs @@ -472,11 +472,11 @@ fn make_block( } fn oneway(ty: Type) -> Vec { - vec![Type::new_sum([vec![ty].into()])] + vec![Type::new_sum([vec![ty]])] } fn twoway(ty: Type) -> Vec { - vec![Type::new_sum([vec![ty.clone()].into(), vec![ty].into()])] + vec![Type::new_sum([vec![ty.clone()], vec![ty]])] } fn create_entry_exit( diff --git a/hugr-core/src/hugr/serialize/test.rs b/hugr-core/src/hugr/serialize/test.rs index d86ee810f..f994eb2b0 100644 --- a/hugr-core/src/hugr/serialize/test.rs +++ b/hugr-core/src/hugr/serialize/test.rs @@ -426,7 +426,7 @@ fn roundtrip_sumtype(#[case] sum_type: SumType) { #[case(Value::true_val())] #[case(Value::unit_sum(3,5).unwrap())] #[case(Value::extension(ConstInt::new_u(2,1).unwrap()))] -#[case(Value::sum(1,[Value::extension(ConstInt::new_u(2,1).unwrap())], SumType::new([vec![], vec![INT_TYPES[2].clone().into()]])).unwrap())] +#[case(Value::sum(1,[Value::extension(ConstInt::new_u(2,1).unwrap())], SumType::new([vec![], vec![INT_TYPES[2].clone()]])).unwrap())] #[case(Value::tuple([Value::false_val(), Value::extension(ConstInt::new_s(2,1).unwrap())]))] #[case(Value::function(crate::builder::test::simple_dfg_hugr()).unwrap())] fn roundtrip_value(#[case] value: Value) { diff --git a/hugr-core/src/ops/leaf.rs b/hugr-core/src/ops/leaf.rs index f183e8a9d..0e345669f 100644 --- a/hugr-core/src/ops/leaf.rs +++ b/hugr-core/src/ops/leaf.rs @@ -144,7 +144,7 @@ impl DataflowOpTrait for MakeTuple { /// The signature of the operation. fn signature(&self) -> FunctionType { - FunctionType::new(self.tys.clone(), vec![Type::new_tuple(self.tys.clone().into_())]) + FunctionType::new(self.tys.clone(), vec![Type::new_tuple(self.tys.clone())]) } fn other_input(&self) -> Option { @@ -166,7 +166,7 @@ impl DataflowOpTrait for UnpackTuple { /// The signature of the operation. fn signature(&self) -> FunctionType { - FunctionType::new(vec![Type::new_tuple(self.tys.clone().into_())], self.tys.clone()) + FunctionType::new(vec![Type::new_tuple(self.tys.clone())], self.tys.clone()) } fn other_input(&self) -> Option { diff --git a/hugr-core/src/std_extensions/arithmetic/conversions.rs b/hugr-core/src/std_extensions/arithmetic/conversions.rs index a6a28ee63..13e164672 100644 --- a/hugr-core/src/std_extensions/arithmetic/conversions.rs +++ b/hugr-core/src/std_extensions/arithmetic/conversions.rs @@ -47,11 +47,11 @@ impl MakeOpDef for ConvertOpDef { match self { trunc_s | trunc_u => FunTypeVarArgs::new( - type_row![FLOAT64_TYPE].into_(), + type_row![FLOAT64_TYPE], Type::::from(sum_with_error(int_tv(0))) ), convert_s | convert_u => - FunTypeVarArgs::new(vec![int_tv(0)], type_row![FLOAT64_TYPE].into_()) + FunTypeVarArgs::new(vec![int_tv(0)], type_row![FLOAT64_TYPE]) }).into() } diff --git a/hugr-core/src/std_extensions/arithmetic/int_ops.rs b/hugr-core/src/std_extensions/arithmetic/int_ops.rs index 4a4b42345..b005a92e0 100644 --- a/hugr-core/src/std_extensions/arithmetic/int_ops.rs +++ b/hugr-core/src/std_extensions/arithmetic/int_ops.rs @@ -116,10 +116,10 @@ impl MakeOpDef for IntOpDef { IOValidator { f_ge_s: true }, ) .into(), - itobool => int_polytype(0, vec![int_type(0)], type_row![BOOL_T].into_()).into(), - ifrombool => int_polytype(0, type_row![BOOL_T].into_(), vec![int_type(0)]).into(), + itobool => int_polytype(0, vec![int_type(0)], type_row![BOOL_T]).into(), + ifrombool => int_polytype(0, type_row![BOOL_T], vec![int_type(0)]).into(), ieq | ine | ilt_u | ilt_s | igt_u | igt_s | ile_u | ile_s | ige_u | ige_s => { - int_polytype(1, vec![int_tv(0); 2], type_row![BOOL_T].into_()).into() + int_polytype(1, vec![int_tv(0); 2], type_row![BOOL_T]).into() } imax_u | imax_s | imin_u | imin_s | iadd | isub | imul | iand | ior | ixor => { ibinop_sig().into() diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index 3ea350a3e..d189d6d6f 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -573,13 +573,13 @@ pub(crate) fn check_typevar_decl( pub(crate) mod test { use super::*; - + use crate::type_row; use crate::extension::prelude::USIZE_T; #[test] fn construct() { let t: Type = Type::new_tuple(vec![ - USIZE_T.into(), + USIZE_T, Type::new_function(FunctionType::new_endo(vec![])), Type::new_extension(CustomType::new( "my_custom", @@ -596,14 +596,15 @@ pub(crate) mod test { } #[rstest::rstest] - fn sum_construct() { - let pred1: Type = Type::new_sum([Type::EMPTY_TYPEROW, Type::EMPTY_TYPEROW]); + fn sum_construct() { + let pred1: Type = Type::new_sum([type_row![], type_row![]]); let pred2: Type = Type::new_unit_sum(2); assert_eq!(pred1, pred2); let pred_direct = SumType::Unit { size: 2 }; - assert_eq!(pred1, pred_direct.into()) + // Pick arbitrarily + assert_eq!(pred1, Type::::from(pred_direct)); } mod proptest { diff --git a/hugr-core/src/types/type_param.rs b/hugr-core/src/types/type_param.rs index e89501079..b4a8fe55e 100644 --- a/hugr-core/src/types/type_param.rs +++ b/hugr-core/src/types/type_param.rs @@ -226,6 +226,9 @@ pub struct TypeArgVariable { } impl TypeArg { + /// [Type::UNIT] as a [TypeArg::Type] + pub const UNIT: Self = Self::Type {ty: Type::UNIT}; + /// Makes a TypeArg representing a use (occurrence) of the type variable /// with the specified index. /// `decl` must be exactly that with which the variable was declared. @@ -533,7 +536,8 @@ mod test { #[test] fn type_arg_subst_row() { let row_param = TypeParam::new_list(TypeBound::Copyable); - let row_arg: TypeArg = vec![BOOL_T.into(), Type::UNIT.into()].into(); + // The here is arbitrary but we have to specify it: + let row_arg: TypeArg = vec![BOOL_T.into(), TypeArg::UNIT].into(); check_type_arg(&row_arg, &row_param).unwrap(); // Now say a row variable referring to *that* row was used @@ -550,7 +554,7 @@ mod test { let outer_arg2 = outer_arg.substitute(&Substitution(&[row_arg], &PRELUDE_REGISTRY)); assert_eq!( outer_arg2, - vec![BOOL_T.into(), Type::UNIT.into(), USIZE_T.into()].into() + vec![BOOL_T.into(), TypeArg::UNIT, USIZE_T.into()].into() ); // Of course this is still valid (as substitution is guaranteed to preserve validity) diff --git a/hugr-core/src/types/type_row.rs b/hugr-core/src/types/type_row.rs index 194267a24..c3abaf0ff 100644 --- a/hugr-core/src/types/type_row.rs +++ b/hugr-core/src/types/type_row.rs @@ -175,6 +175,13 @@ impl From> for TypeRow { } } +impl From for TypeRow { + fn from(value: TypeRow) -> Self { + Self { + types: value.into_iter().cloned().map(Type::into_).collect() + } + } +} impl From<&'static [Type]> for TypeRow { fn from(types: &'static [Type]) -> Self { diff --git a/hugr-passes/src/const_fold.rs b/hugr-passes/src/const_fold.rs index 9f496de32..ba52685f2 100644 --- a/hugr-passes/src/const_fold.rs +++ b/hugr-passes/src/const_fold.rs @@ -64,7 +64,7 @@ pub fn fold_leaf_op(op: &OpType, consts: &[(IncomingPort, Value)]) -> ConstFoldR OpType::Tag(t) => out_row([Value::sum( t.tag, consts.iter().map(|(_, konst)| konst.clone()), - SumType::new(t.variants.clone().into_iter().map(TypeRow::into_)), + SumType::new(t.variants.clone()), ) .unwrap()]), OpType::CustomOp(op) => { From 68fac6085617278a9a0637baadff443f9f9937bb Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 11 Jun 2024 16:08:53 +0100 Subject: [PATCH 062/115] Fix proptest Arbitrary's --- hugr-core/src/types.rs | 5 +++-- hugr-core/src/types/poly_func.rs | 2 +- hugr-core/src/types/signature.rs | 4 ++-- hugr-core/src/types/type_row.rs | 8 ++++---- 4 files changed, 10 insertions(+), 9 deletions(-) diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index d189d6d6f..74bb98c0d 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -215,7 +215,7 @@ pub enum TypeEnum { Function( #[cfg_attr( test, - proptest(strategy = "any_with::(params).prop_map(Box::new)") + proptest(strategy = "any_with::(params).prop_map(Box::new)") )] Box, ), @@ -629,12 +629,13 @@ pub(crate) mod test { } } - impl Arbitrary for super::Type { + impl Arbitrary for super::Type { type Parameters = RecursionDepth; type Strategy = BoxedStrategy; fn arbitrary_with(depth: Self::Parameters) -> Self::Strategy { // We descend here, because a TypeEnum may contain a Type any_with::(depth.descend()) + .prop_filter("Type cannot be a Row Variable", |t| RV || !matches!(t, TypeEnum::RowVariable(_,_))) .prop_map(Self::new) .boxed() } diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index 8bdd78533..987e9e8c4 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -35,7 +35,7 @@ pub struct PolyFuncType { #[cfg_attr(test, proptest(strategy = "vec(any_with::(params), 0..3)"))] params: Vec, /// Template for the function. May contain variables up to length of [Self::params] - #[cfg_attr(test, proptest(strategy = "any_with::(params)"))] + #[cfg_attr(test, proptest(strategy = "any_with::>(params)"))] body: FuncTypeBase, } diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index cdcd44b49..88034de61 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -25,10 +25,10 @@ use {crate::proptest::RecursionDepth, ::proptest::prelude::*, proptest_derive::A /// [RowVariable]: crate::types::TypeEnum::RowVariable pub struct FuncTypeBase { /// Value inputs of the function. - #[cfg_attr(test, proptest(strategy = "any_with::(params)"))] + #[cfg_attr(test, proptest(strategy = "any_with::>(params)"))] pub input: TypeRow, /// Value outputs of the function. - #[cfg_attr(test, proptest(strategy = "any_with::(params)"))] + #[cfg_attr(test, proptest(strategy = "any_with::>(params)"))] pub output: TypeRow, /// The extension requirements which are added by the operation pub extension_reqs: ExtensionSet, diff --git a/hugr-core/src/types/type_row.rs b/hugr-core/src/types/type_row.rs index c3abaf0ff..a81b7d018 100644 --- a/hugr-core/src/types/type_row.rs +++ b/hugr-core/src/types/type_row.rs @@ -225,18 +225,18 @@ impl DerefMut for TypeRow { mod test { mod proptest { use crate::proptest::RecursionDepth; - use crate::{type_row, types::Type}; + use crate::types::{TypeRow, Type}; use ::proptest::prelude::*; - impl Arbitrary for super::super::TypeRow { + impl Arbitrary for super::super::TypeRow { type Parameters = RecursionDepth; type Strategy = BoxedStrategy; fn arbitrary_with(depth: Self::Parameters) -> Self::Strategy { use proptest::collection::vec; if depth.leaf() { - Just(type_row![]).boxed() + Just(TypeRow::new()).boxed() } else { - vec(any_with::(depth), 0..4) + vec(any_with::>(depth), 0..4) .prop_map(|ts| ts.to_vec().into()) .boxed() } From 0b492b3fe9911d6f5d3bb80ae90df09043797618 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 11 Jun 2024 17:42:08 +0100 Subject: [PATCH 063/115] dataflow.rs test (does this now duplicate validate?) --- hugr-core/src/builder/dataflow.rs | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/hugr-core/src/builder/dataflow.rs b/hugr-core/src/builder/dataflow.rs index 7dc4886a6..3c95bd38b 100644 --- a/hugr-core/src/builder/dataflow.rs +++ b/hugr-core/src/builder/dataflow.rs @@ -559,7 +559,8 @@ pub(crate) mod test { fn no_outer_row_variables() -> Result<(), BuildError> { let e = crate::hugr::validate::test::extension_with_eval_parallel(); let tv = Type::new_row_var_use(0, TypeBound::Copyable); - let mut fb = FunctionBuilder::new( + // Can *declare* a function that takes a function-value of unknown #args + let fb = FunctionBuilder::new( "bad_eval", PolyFuncType::new( [TypeParam::new_list(TypeBound::Copyable)], @@ -570,19 +571,13 @@ pub(crate) mod test { ), )?; - let [func_arg] = fb.input_wires_arr(); - let i = fb.add_load_value(crate::extension::prelude::ConstUsize::new(5)); + // But cannot eval it... let ev = e.instantiate_extension_op( "eval", [vec![USIZE_T.into()].into(), vec![tv.into()].into()], &PRELUDE_REGISTRY, - )?; - let r = fb.add_dataflow_op(ev, [func_arg, i]); - // This error would be caught in validation, but the builder detects it much earlier - assert_eq!( - r.unwrap_err(), - BuildError::SignatureError(SignatureError::RowVarWhereTypeExpected { idx: 0 }) ); + assert!(ev.is_err()); Ok(()) } } From a1d1574fb40d88b948d3ee737fb2a1f228be3ad2 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 11 Jun 2024 18:28:06 +0100 Subject: [PATCH 064/115] fix substitution logic --- hugr-core/src/types.rs | 19 ++++++++++------ hugr-core/src/types/type_param.rs | 36 ++++++++++++++++++++++--------- 2 files changed, 39 insertions(+), 16 deletions(-) diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index 74bb98c0d..e40e247c1 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -415,9 +415,9 @@ impl Type { fn substitute(&self, t: &Substitution) -> Vec { match &self.0 { TypeEnum::RowVariable(idx, bound) => { - assert!(RV); let res = t.apply_rowvar(*idx, *bound); // these are Type's - // We need Types, so use try_into_(). Since we know RV==true, this cannot fail. + assert!(RV); + // We need Types, so use try_into_(). Since we know RV==true, this cannot fail. res.into_iter().map(|t| t.try_into_().unwrap()).collect() } TypeEnum::Alias(_) | TypeEnum::Sum(SumType::Unit { .. }) => vec![self.clone()], @@ -523,12 +523,19 @@ impl<'a> Substitution<'a> { .expect("Undeclared type variable - call validate() ?"); debug_assert!(check_type_arg(arg, &TypeParam::new_list(bound)).is_ok()); match arg { - // Row variables are represented as 'TypeArg::Type's (see TypeArg::new_var_use) TypeArg::Sequence { elems } => elems .iter() - .map(|ta| match ta { - TypeArg::Type { ty } => ty.clone().into(), - _ => panic!("Not a list of types - call validate() ?"), + .map(|ta| { + match ta { + TypeArg::Type { ty } => return ty.clone().into(), + TypeArg::Variable { v } => { + if let Some(b) = v.bound_if_row_var() { + return Type::new_row_var_use(v.index(), b) + } + } + _ => () + } + panic!("Not a list of types - call validate() ?") }) .collect(), TypeArg::Type { ty } if matches!(ty.0, TypeEnum::RowVariable(_, _)) => { diff --git a/hugr-core/src/types/type_param.rs b/hugr-core/src/types/type_param.rs index b4a8fe55e..7726b634a 100644 --- a/hugr-core/src/types/type_param.rs +++ b/hugr-core/src/types/type_param.rs @@ -302,7 +302,11 @@ impl TypeArg { self.clone() } TypeArg::Sequence { elems } => { - let mut are_types = elems.iter().map(|e| matches!(e, TypeArg::Type { .. })); + let mut are_types = elems.iter().map(|ta| match ta { + TypeArg::Type {..} => true, + TypeArg::Variable { v } => v.bound_if_row_var().is_some(), + _ => false + }); let elems = match are_types.next() { Some(true) => { assert!(are_types.all(|b| b)); // If one is a Type, so must the rest be @@ -338,6 +342,16 @@ impl TypeArgVariable { pub fn index(&self) -> usize { self.idx } + + pub fn bound_if_row_var(&self) -> Option { + if let TypeParam::List {param} = &self.cached_decl { + if let TypeParam::Type {b} = **param { + return Some(b) + } + } + None + } + } /// A serialized representation of a value of a [CustomType] @@ -378,16 +392,18 @@ pub fn check_type_arg(arg: &TypeArg, param: &TypeParam) -> Result<(), TypeArgErr Ok(()) } (TypeArg::Sequence { elems }, TypeParam::List { param }) => { - elems.iter().try_for_each(|arg| check_type_arg(arg, param)) + elems.iter().try_for_each(|arg| { + // Also allow elements that are RowVars if fitting into a List of Types + if let (TypeArg::Variable { v: TypeArgVariable { idx: _, cached_decl: TypeParam::List { param: arg_var} } }, TypeParam::Type { b: param_bound }) = (arg, &**param) { + if let TypeParam::Type {b: var_bound} = **arg_var { + if param_bound.contains(var_bound) { + return Ok(()); + } + } + } + check_type_arg(arg, param) + }) } - // Also allow a single "Type" to be used for a List *only* if the Type is a row variable - // (i.e., it's not really a Type, it's multiple Types) - /* ALAN this is impossible, but what's it look like now? - (TypeArg::Type { ty }, TypeParam::List { param }) - if ty.is_row_var() && param.contains(&ty.least_upper_bound().into()) => - { - Ok(()) - }*/ (TypeArg::Sequence { elems: items }, TypeParam::Tuple { params: types }) => { if items.len() != types.len() { Err(TypeArgError::WrongNumberTuple(items.len(), types.len())) From d723076e751024a888ceb288197f169d8a5f9ee4 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 11 Jun 2024 18:33:02 +0100 Subject: [PATCH 065/115] Fix doctests --- hugr-core/src/types.rs | 4 ++-- hugr-core/src/utils.rs | 6 +++--- hugr/src/lib.rs | 8 ++++---- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index e40e247c1..7bceffb8f 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -271,14 +271,14 @@ impl Implies { /// # use hugr::types::{Type, TypeBound}; /// # use hugr::type_row; /// -/// let sum = Type::new_sum([type_row![], type_row![]]); +/// let sum: Type = Type::new_sum([type_row![], type_row![]]); /// assert_eq!(sum.least_upper_bound(), TypeBound::Eq); /// ``` /// /// ``` /// # use hugr::types::{Type, TypeBound, FunctionType}; /// -/// let func_type = Type::new_function(FunctionType::new_endo(vec![])); +/// let func_type: Type = Type::new_function(FunctionType::new_endo(vec![])); /// assert_eq!(func_type.least_upper_bound(), TypeBound::Copyable); /// ``` pub struct Type(TypeEnum, TypeBound); diff --git a/hugr-core/src/utils.rs b/hugr-core/src/utils.rs index 5c8172729..96877e01b 100644 --- a/hugr-core/src/utils.rs +++ b/hugr-core/src/utils.rs @@ -103,6 +103,7 @@ pub(crate) fn is_default(t: &T) -> bool { #[cfg(test)] pub(crate) mod test_quantum_extension { use crate::ops::{OpName, OpNameRef}; + use crate::types::FunTypeVarArgs; use crate::{ extension::{ prelude::{BOOL_T, QB_T}, @@ -118,12 +119,11 @@ pub(crate) mod test_quantum_extension { use lazy_static::lazy_static; fn one_qb_func() -> PolyFuncType { - PolyFuncType::new(vec![], FunctionType::new_endo(QB_T)) + FunTypeVarArgs::new_endo(QB_T).into() } fn two_qb_func() -> PolyFuncType { - // ALAN this and prev would be easier with TypeRow -> TypeRow - PolyFuncType::new(vec![], FunctionType::new_endo(type_row![QB_T, QB_T])) + FunTypeVarArgs::new_endo(type_row![QB_T, QB_T]).into() } /// The extension identifier. pub const EXTENSION_ID: ExtensionId = ExtensionId::new_unchecked("test.quantum"); diff --git a/hugr/src/lib.rs b/hugr/src/lib.rs index 7e2562cf3..c874d448c 100644 --- a/hugr/src/lib.rs +++ b/hugr/src/lib.rs @@ -43,18 +43,18 @@ //! }, //! ops::{CustomOp, OpName}, //! type_row, -//! types::{FunctionType, PolyFuncType}, +//! types::{FunTypeVarArgs, PolyFuncType}, //! Extension, //! }; //! //! use lazy_static::lazy_static; //! //! fn one_qb_func() -> PolyFuncType { -//! FunctionType::new_endo(type_row![QB_T]).into() +//! FunTypeVarArgs::new_endo(type_row![QB_T]).into() //! } //! //! fn two_qb_func() -> PolyFuncType { -//! FunctionType::new_endo(type_row![QB_T, QB_T]).into() +//! FunTypeVarArgs::new_endo(type_row![QB_T, QB_T]).into() //! } //! /// The extension identifier. //! pub const EXTENSION_ID: ExtensionId = ExtensionId::new_unchecked("mini.quantum"); @@ -73,7 +73,7 @@ //! .add_op( //! OpName::new_inline("Measure"), //! "Measure a qubit, returning the qubit and the measurement result.".into(), -//! FunctionType::new(type_row![QB_T], type_row![QB_T, BOOL_T]), +//! FunTypeVarArgs::new(type_row![QB_T], type_row![QB_T, BOOL_T]), //! ) //! .unwrap(); //! From 2e9a28471a6b49853b74c7bc56378b53d8793e19 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 11 Jun 2024 18:39:33 +0100 Subject: [PATCH 066/115] clippy/lint --- hugr-core/src/builder/dataflow.rs | 4 ++-- hugr-core/src/extension/declarative/signature.rs | 2 +- hugr-core/src/hugr/validate/test.rs | 1 - hugr-core/src/std_extensions/arithmetic/int_ops.rs | 4 ++-- hugr-core/src/types/poly_func.rs | 2 +- hugr-core/src/types/type_row.rs | 2 +- hugr-passes/src/const_fold.rs | 2 +- hugr/benches/benchmarks/types.rs | 4 ++-- 8 files changed, 10 insertions(+), 11 deletions(-) diff --git a/hugr-core/src/builder/dataflow.rs b/hugr-core/src/builder/dataflow.rs index 3c95bd38b..a63f396ed 100644 --- a/hugr-core/src/builder/dataflow.rs +++ b/hugr-core/src/builder/dataflow.rs @@ -212,7 +212,7 @@ pub(crate) mod test { use crate::builder::build_traits::DataflowHugr; use crate::builder::{BuilderWiringError, DataflowSubContainer, ModuleBuilder}; use crate::extension::prelude::{BOOL_T, USIZE_T}; - use crate::extension::{ExtensionId, SignatureError, EMPTY_REG, PRELUDE_REGISTRY}; + use crate::extension::{ExtensionId, EMPTY_REG, PRELUDE_REGISTRY}; use crate::hugr::validate::InterGraphEdgeError; use crate::ops::{handle::NodeHandle, Lift, Noop, OpTag}; @@ -560,7 +560,7 @@ pub(crate) mod test { let e = crate::hugr::validate::test::extension_with_eval_parallel(); let tv = Type::new_row_var_use(0, TypeBound::Copyable); // Can *declare* a function that takes a function-value of unknown #args - let fb = FunctionBuilder::new( + FunctionBuilder::new( "bad_eval", PolyFuncType::new( [TypeParam::new_list(TypeBound::Copyable)], diff --git a/hugr-core/src/extension/declarative/signature.rs b/hugr-core/src/extension/declarative/signature.rs index 5ac1de0c4..45047f016 100644 --- a/hugr-core/src/extension/declarative/signature.rs +++ b/hugr-core/src/extension/declarative/signature.rs @@ -12,7 +12,7 @@ use serde::{Deserialize, Serialize}; use smol_str::SmolStr; use crate::extension::prelude::PRELUDE_ID; -use crate::extension::{CustomValidator, ExtensionSet, SignatureFunc, TypeDef}; +use crate::extension::{ExtensionSet, SignatureFunc, TypeDef}; use crate::types::type_param::TypeParam; use crate::types::{CustomType, FunTypeVarArgs, PolyFuncType, Type, TypeRow}; use crate::Extension; diff --git a/hugr-core/src/hugr/validate/test.rs b/hugr-core/src/hugr/validate/test.rs index f20ea9f2b..0515d867b 100644 --- a/hugr-core/src/hugr/validate/test.rs +++ b/hugr-core/src/hugr/validate/test.rs @@ -1,5 +1,4 @@ use cool_asserts::assert_matches; -use rstest::rstest; use super::*; use crate::builder::test::closed_dfg_root_hugr; diff --git a/hugr-core/src/std_extensions/arithmetic/int_ops.rs b/hugr-core/src/std_extensions/arithmetic/int_ops.rs index b005a92e0..061a0de28 100644 --- a/hugr-core/src/std_extensions/arithmetic/int_ops.rs +++ b/hugr-core/src/std_extensions/arithmetic/int_ops.rs @@ -10,7 +10,7 @@ use crate::ops::custom::ExtensionOp; use crate::ops::{NamedOp, OpName}; use crate::std_extensions::arithmetic::int_types::int_type; use crate::type_row; -use crate::types::{FunTypeVarArgs, FunctionType, PolyFuncType}; +use crate::types::{FunTypeVarArgs, PolyFuncType}; use crate::utils::collect_array; use crate::{ @@ -353,7 +353,7 @@ fn sum_ty_with_err(t: Type) -> Type { #[cfg(test)] mod test { - use crate::{ops::dataflow::DataflowOpTrait, std_extensions::arithmetic::int_types::int_type}; + use crate::{ops::dataflow::DataflowOpTrait, std_extensions::arithmetic::int_types::int_type, types::FunctionType}; use super::*; diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index 987e9e8c4..f30109718 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -9,7 +9,7 @@ use { proptest_derive::Arbitrary, }; -use super::signature::{FuncTypeBase, FunctionType}; +use super::signature::{FuncTypeBase}; use super::type_param::{check_type_args, TypeArg, TypeParam}; use super::Substitution; diff --git a/hugr-core/src/types/type_row.rs b/hugr-core/src/types/type_row.rs index a81b7d018..7abd98002 100644 --- a/hugr-core/src/types/type_row.rs +++ b/hugr-core/src/types/type_row.rs @@ -178,7 +178,7 @@ impl From> for TypeRow { impl From for TypeRow { fn from(value: TypeRow) -> Self { Self { - types: value.into_iter().cloned().map(Type::into_).collect() + types: value.iter().cloned().map(Type::into_).collect() } } } diff --git a/hugr-passes/src/const_fold.rs b/hugr-passes/src/const_fold.rs index ba52685f2..01c68722c 100644 --- a/hugr-passes/src/const_fold.rs +++ b/hugr-passes/src/const_fold.rs @@ -6,7 +6,7 @@ use itertools::Itertools; use thiserror::Error; use hugr_core::hugr::{SimpleReplacementError, ValidationError}; -use hugr_core::types::{SumType, TypeRow}; +use hugr_core::types::{SumType}; use hugr_core::Direction; use hugr_core::{ builder::{DFGBuilder, Dataflow, DataflowHugr}, diff --git a/hugr/benches/benchmarks/types.rs b/hugr/benches/benchmarks/types.rs index 3b599983c..3698a2aed 100644 --- a/hugr/benches/benchmarks/types.rs +++ b/hugr/benches/benchmarks/types.rs @@ -10,10 +10,10 @@ use criterion::{black_box, criterion_group, AxisScale, Criterion, PlotConfigurat fn make_complex_type() -> Type { let qb = QB_T; let int = USIZE_T; - let q_register = Type::new_tuple(vec![qb; 8]); + let q_register: Type = 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)); - let sum = Type::new_sum([vec![q_register].into(), vec![q_alias].into()]); + let sum: Type = Type::new_sum([q_register, q_alias]); Type::new_function(FunctionType::new(vec![sum], vec![b_register])) } From e74018479bf9ff4383bbc40f5e25312dc58b95c0 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 11 Jun 2024 18:43:16 +0100 Subject: [PATCH 067/115] Drop FunctionType.into_(), we have impl Into now --- hugr-core/src/extension/op_def.rs | 2 +- hugr-core/src/ops/constant.rs | 2 +- hugr-core/src/ops/dataflow.rs | 4 ++-- hugr-core/src/types/poly_func.rs | 2 +- hugr-core/src/types/signature.rs | 8 -------- 5 files changed, 5 insertions(+), 13 deletions(-) diff --git a/hugr-core/src/extension/op_def.rs b/hugr-core/src/extension/op_def.rs index d99a4319a..afbfe6228 100644 --- a/hugr-core/src/extension/op_def.rs +++ b/hugr-core/src/extension/op_def.rs @@ -200,7 +200,7 @@ impl From for SignatureFunc { impl From for SignatureFunc { fn from(v: FunctionType) -> Self { - Self::TypeScheme(CustomValidator::from_polyfunc(v.into_())) + Self::TypeScheme(CustomValidator::from_polyfunc(FunTypeVarArgs::from(v))) } } diff --git a/hugr-core/src/ops/constant.rs b/hugr-core/src/ops/constant.rs index c338f1a1d..28913d795 100644 --- a/hugr-core/src/ops/constant.rs +++ b/hugr-core/src/ops/constant.rs @@ -287,7 +287,7 @@ impl Value { Self::Sum { sum_type, .. } => sum_type.clone().into(), Self::Function { hugr } => { let func_type = mono_fn_type(hugr).unwrap_or_else(|e| panic!("{}", e)); - Type::new_function(func_type.into_()) + Type::new_function(func_type) } } } diff --git a/hugr-core/src/ops/dataflow.rs b/hugr-core/src/ops/dataflow.rs index e242f3eae..d52209602 100644 --- a/hugr-core/src/ops/dataflow.rs +++ b/hugr-core/src/ops/dataflow.rs @@ -268,7 +268,7 @@ impl DataflowOpTrait for CallIndirect { let mut s = self.signature.clone(); s.input .to_mut() - .insert(0, Type::new_function(self.signature.clone().into_())); + .insert(0, Type::new_function(self.signature.clone())); s } } @@ -360,7 +360,7 @@ impl LoadFunction { exts: &ExtensionRegistry, ) -> Result { let type_args = type_args.into(); - let instantiation = func_sig.instantiate(&type_args, exts)?.into_(); + let instantiation = func_sig.instantiate(&type_args, exts)?; let signature = FunctionType::new(TypeRow::new(), vec![Type::new_function(instantiation)]); Ok(Self { func_sig, diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index f30109718..be17d8871 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -52,7 +52,7 @@ impl From> for PolyFuncType { fn from(value: PolyFuncType) -> Self { Self { params: value.params, - body: value.body.into_() + body: value.body.into() } } } diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index 88034de61..0e154139a 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -114,14 +114,6 @@ impl FunTypeVarArgs { } impl FunctionType { - pub(crate) fn into_(self) -> FunTypeVarArgs { - FunTypeVarArgs { - input: self.input.into_(), - output: self.output.into_(), - extension_reqs: self.extension_reqs - } - } - /// Returns the type of a value [`Port`]. Returns `None` if the port is out /// of bounds. #[inline] From b109271da254bb5fda5f58807e577de1bf83acec Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 11 Jun 2024 18:46:38 +0100 Subject: [PATCH 068/115] Drop TypeRow::into_, similarly --- hugr-core/src/types/signature.rs | 4 ++-- hugr-core/src/types/type_row.rs | 13 +------------ 2 files changed, 3 insertions(+), 14 deletions(-) diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index 0e154139a..53ea4ea69 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -253,8 +253,8 @@ impl TryFrom for FunctionType { impl From for FunTypeVarArgs { fn from(value: FunctionType) -> Self { Self { - input: value.input.into_(), - output: value.output.into_(), + input: value.input.into(), + output: value.output.into(), extension_reqs: value.extension_reqs } } diff --git a/hugr-core/src/types/type_row.rs b/hugr-core/src/types/type_row.rs index 7abd98002..4c5fddcc4 100644 --- a/hugr-core/src/types/type_row.rs +++ b/hugr-core/src/types/type_row.rs @@ -7,7 +7,7 @@ use std::{ ops::{Deref, DerefMut}, }; -use super::{type_param::TypeParam, Implies, Substitution, Type}; +use super::{type_param::TypeParam, Substitution, Type}; use crate::{ extension::{ExtensionRegistry, SignatureError}, utils::display_list, @@ -94,17 +94,6 @@ impl TypeRow { ) -> Result<(), SignatureError> { self.iter().try_for_each(|t| t.validate(exts, var_decls)) } - - pub fn into_(self) -> TypeRow { - let _ = Implies::::A_IMPLIES_B; - TypeRow::from( - self.types - .iter() - .cloned() - .map(Type::into_) - .collect::>(), - ) - } } impl TypeRow { From 8c3aa91a6d4182d3a3ecf8af4ee1dcf6e6875eb4 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 11 Jun 2024 18:49:49 +0100 Subject: [PATCH 069/115] Hide Type::into_, allow let_unit_value; and method docs --- hugr-core/src/types.rs | 6 +++++- hugr-core/src/types/type_param.rs | 2 ++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index 7bceffb8f..cbf967c0a 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -483,7 +483,11 @@ impl Type { Ok(Type(self.0, self.1)) } - pub fn into_(self) -> Type { + /// A swiss-army-knife for any safe conversion of the const-bool "type" argument + /// to/from true/false/variable. Any unsafe conversion (that might create + /// a [Type]`` of a [TypeEnum::RowVariable] will fail statically with an assert. + fn into_(self) -> Type { + #[allow(clippy::let_unit_value)] let _ = Implies::::A_IMPLIES_B; Type(self.0, self.1) } diff --git a/hugr-core/src/types/type_param.rs b/hugr-core/src/types/type_param.rs index 7726b634a..765f9f786 100644 --- a/hugr-core/src/types/type_param.rs +++ b/hugr-core/src/types/type_param.rs @@ -343,6 +343,8 @@ impl TypeArgVariable { self.idx } + /// Determines whether this represents a row variable; if so, returns + /// the [TypeBound] of the individual types it might stand for. pub fn bound_if_row_var(&self) -> Option { if let TypeParam::List {param} = &self.cached_decl { if let TypeParam::Type {b} = **param { From 9ea9c61537a57a3a4f56558c4f8cbb137af23960 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 11 Jun 2024 19:11:19 +0100 Subject: [PATCH 070/115] Fix...and then fmt, oops --- hugr-core/src/builder/build_traits.rs | 2 +- hugr-core/src/builder/dataflow.rs | 2 +- hugr-core/src/extension/prelude.rs | 2 +- hugr-core/src/extension/type_def.rs | 3 +- hugr-core/src/hugr/serialize/test.rs | 4 +- hugr-core/src/hugr/validate.rs | 2 +- hugr-core/src/hugr/validate/test.rs | 4 +- hugr-core/src/ops/module.rs | 2 +- .../std_extensions/arithmetic/conversions.rs | 16 ++++--- .../src/std_extensions/arithmetic/int_ops.rs | 14 +++--- hugr-core/src/types.rs | 27 +++++++----- hugr-core/src/types/poly_func.rs | 15 ++++--- hugr-core/src/types/signature.rs | 4 +- hugr-core/src/types/type_param.rs | 43 +++++++++++++------ hugr-core/src/types/type_row.rs | 14 +++--- hugr-passes/src/const_fold.rs | 2 +- hugr-passes/src/merge_bbs.rs | 5 ++- 17 files changed, 97 insertions(+), 64 deletions(-) diff --git a/hugr-core/src/builder/build_traits.rs b/hugr-core/src/builder/build_traits.rs index 91b863722..03c7f165d 100644 --- a/hugr-core/src/builder/build_traits.rs +++ b/hugr-core/src/builder/build_traits.rs @@ -20,7 +20,7 @@ use crate::{ }; use crate::extension::{ExtensionRegistry, ExtensionSet, PRELUDE_REGISTRY}; -use crate::types::{PolyFuncType, FunctionType, Type, TypeArg, TypeRow}; +use crate::types::{FunctionType, PolyFuncType, Type, TypeArg, TypeRow}; use itertools::Itertools; diff --git a/hugr-core/src/builder/dataflow.rs b/hugr-core/src/builder/dataflow.rs index a63f396ed..12f0a9fc9 100644 --- a/hugr-core/src/builder/dataflow.rs +++ b/hugr-core/src/builder/dataflow.rs @@ -7,7 +7,7 @@ use std::marker::PhantomData; use crate::hugr::{HugrView, NodeType, ValidationError}; use crate::ops; -use crate::types::{PolyFuncType, FunctionType}; +use crate::types::{FunctionType, PolyFuncType}; use crate::extension::{ExtensionRegistry, ExtensionSet}; use crate::Node; diff --git a/hugr-core/src/extension/prelude.rs b/hugr-core/src/extension/prelude.rs index acf66d7df..69f513825 100644 --- a/hugr-core/src/extension/prelude.rs +++ b/hugr-core/src/extension/prelude.rs @@ -544,7 +544,7 @@ mod test { #[test] fn test_external_symbol() { let subject = ConstExternalSymbol::new("foo", Type::UNIT, false); - assert_eq!(subject.get_type(), Type::UNIT); + assert_eq!(subject.get_type(), Type::::UNIT); assert_eq!(subject.name(), "@foo"); assert!(subject.validate().is_ok()); assert_eq!( diff --git a/hugr-core/src/extension/type_def.rs b/hugr-core/src/extension/type_def.rs index 8933baa57..e7fae8bca 100644 --- a/hugr-core/src/extension/type_def.rs +++ b/hugr-core/src/extension/type_def.rs @@ -189,7 +189,8 @@ mod test { .unwrap(), ); assert_eq!(typ.least_upper_bound(), TypeBound::Copyable); - let typ2: Type = Type::new_extension(def.instantiate([TypeArg::Type { ty: USIZE_T }]).unwrap()); + let typ2: Type = + Type::new_extension(def.instantiate([TypeArg::Type { ty: USIZE_T }]).unwrap()); assert_eq!(typ2.least_upper_bound(), TypeBound::Eq); // And some bad arguments...firstly, wrong kind of TypeArg: diff --git a/hugr-core/src/hugr/serialize/test.rs b/hugr-core/src/hugr/serialize/test.rs index 355b53047..f949c6cb7 100644 --- a/hugr-core/src/hugr/serialize/test.rs +++ b/hugr-core/src/hugr/serialize/test.rs @@ -14,7 +14,8 @@ use crate::std_extensions::arithmetic::int_ops::INT_OPS_REGISTRY; use crate::std_extensions::arithmetic::int_types::{self, int_custom_type, ConstInt, INT_TYPES}; use crate::std_extensions::logic::NotOp; use crate::types::{ - type_param::TypeParam, FunctionType, FunTypeVarArgs, PolyFuncType, SumType, Type, TypeArg, TypeBound, + type_param::TypeParam, FunTypeVarArgs, FunctionType, PolyFuncType, SumType, Type, TypeArg, + TypeBound, }; use crate::{type_row, OutgoingPort}; @@ -102,7 +103,6 @@ impl From> for TestingModel { } } - #[cfg(test)] impl From> for TestingModel { fn from(v: Type) -> Self { diff --git a/hugr-core/src/hugr/validate.rs b/hugr-core/src/hugr/validate.rs index 7ca8a7ab5..10e1bbcaf 100644 --- a/hugr-core/src/hugr/validate.rs +++ b/hugr-core/src/hugr/validate.rs @@ -15,7 +15,7 @@ use crate::ops::custom::{resolve_opaque_op, CustomOp, CustomOpError}; use crate::ops::validate::{ChildrenEdgeData, ChildrenValidationError, EdgeValidationError}; use crate::ops::{FuncDefn, OpParent, OpTag, OpTrait, OpType, ValidateOp}; use crate::types::type_param::TypeParam; -use crate::types::EdgeKind; +use crate::types::{EdgeKind, FunctionType}; use crate::{Direction, Hugr, Node, Port}; use super::views::{HierarchyView, HugrView, SiblingGraph}; diff --git a/hugr-core/src/hugr/validate/test.rs b/hugr-core/src/hugr/validate/test.rs index 87d3c5c54..3e76b1b33 100644 --- a/hugr-core/src/hugr/validate/test.rs +++ b/hugr-core/src/hugr/validate/test.rs @@ -17,7 +17,9 @@ use crate::ops::{self, Noop, OpType, Value}; use crate::std_extensions::logic::test::{and_op, or_op}; use crate::std_extensions::logic::{self, NotOp}; use crate::types::type_param::{TypeArg, TypeArgError}; -use crate::types::{CustomType, FunTypeVarArgs, FunctionType, PolyFuncType, Type, TypeBound, TypeRow}; +use crate::types::{ + CustomType, FunTypeVarArgs, FunctionType, PolyFuncType, Type, TypeBound, TypeRow, +}; use crate::{const_extension_ids, type_row, Direction, IncomingPort, Node}; const NAT: Type = crate::extension::prelude::USIZE_T; diff --git a/hugr-core/src/ops/module.rs b/hugr-core/src/ops/module.rs index d16dc577b..fba1d0609 100644 --- a/hugr-core/src/ops/module.rs +++ b/hugr-core/src/ops/module.rs @@ -7,7 +7,7 @@ use { ::proptest_derive::Arbitrary, }; -use crate::types::{EdgeKind, PolyFuncType, FunctionType}; +use crate::types::{EdgeKind, FunctionType, PolyFuncType}; use crate::types::{Type, TypeBound}; use super::dataflow::DataflowParent; diff --git a/hugr-core/src/std_extensions/arithmetic/conversions.rs b/hugr-core/src/std_extensions/arithmetic/conversions.rs index 13e164672..9e1762e55 100644 --- a/hugr-core/src/std_extensions/arithmetic/conversions.rs +++ b/hugr-core/src/std_extensions/arithmetic/conversions.rs @@ -44,15 +44,17 @@ impl MakeOpDef for ConvertOpDef { use ConvertOpDef::*; PolyFuncType::new( vec![LOG_WIDTH_TYPE_PARAM], - match self { - trunc_s | trunc_u => - FunTypeVarArgs::new( + match self { + trunc_s | trunc_u => FunTypeVarArgs::new( type_row![FLOAT64_TYPE], - Type::::from(sum_with_error(int_tv(0))) + Type::::from(sum_with_error(int_tv(0))), ), - convert_s | convert_u => - FunTypeVarArgs::new(vec![int_tv(0)], type_row![FLOAT64_TYPE]) - }).into() + convert_s | convert_u => { + FunTypeVarArgs::new(vec![int_tv(0)], type_row![FLOAT64_TYPE]) + } + }, + ) + .into() } fn description(&self) -> String { diff --git a/hugr-core/src/std_extensions/arithmetic/int_ops.rs b/hugr-core/src/std_extensions/arithmetic/int_ops.rs index 061a0de28..2bcedf89e 100644 --- a/hugr-core/src/std_extensions/arithmetic/int_ops.rs +++ b/hugr-core/src/std_extensions/arithmetic/int_ops.rs @@ -141,12 +141,9 @@ impl MakeOpDef for IntOpDef { } .into(), idiv_u | idiv_s => int_polytype(2, vec![int_tv(0), int_tv(1)], vec![int_tv(0)]).into(), - idiv_checked_u | idiv_checked_s => int_polytype( - 2, - vec![int_tv(0), int_tv(1)], - sum_ty_with_err(int_tv(0)), - ) - .into(), + idiv_checked_u | idiv_checked_s => { + int_polytype(2, vec![int_tv(0), int_tv(1)], sum_ty_with_err(int_tv(0))).into() + } imod_checked_u | imod_checked_s => int_polytype( 2, vec![int_tv(0), int_tv(1).clone()], @@ -353,7 +350,10 @@ fn sum_ty_with_err(t: Type) -> Type { #[cfg(test)] mod test { - use crate::{ops::dataflow::DataflowOpTrait, std_extensions::arithmetic::int_types::int_type, types::FunctionType}; + use crate::{ + ops::dataflow::DataflowOpTrait, std_extensions::arithmetic::int_types::int_type, + types::FunctionType, + }; use super::*; diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index cbf967c0a..bef3a6d00 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -16,7 +16,7 @@ use crate::utils::display_list_with_separator; pub use check::SumTypeError; pub use custom::CustomType; pub use poly_func::PolyFuncType; -pub use signature::{FunctionType, FunTypeVarArgs}; +pub use signature::{FunTypeVarArgs, FunctionType}; use smol_str::SmolStr; pub use type_param::TypeArg; pub use type_row::TypeRow; @@ -250,8 +250,8 @@ impl TypeEnum { } } -struct Implies(PhantomData>, PhantomData>); -impl Implies { +struct Implies(PhantomData>, PhantomData>); +impl Implies { const A_IMPLIES_B: () = assert!(B || !A); } @@ -314,7 +314,10 @@ impl Type { /// Initialize a new sum type by providing the possible variant types. #[inline(always)] - pub fn new_sum(variants: impl IntoIterator) -> Self where R: Into> { + pub fn new_sum(variants: impl IntoIterator) -> Self + where + R: Into>, + { Self::new(TypeEnum::Sum(SumType::new(variants))) } @@ -486,9 +489,9 @@ impl Type { /// A swiss-army-knife for any safe conversion of the const-bool "type" argument /// to/from true/false/variable. Any unsafe conversion (that might create /// a [Type]`` of a [TypeEnum::RowVariable] will fail statically with an assert. - fn into_(self) -> Type { + fn into_(self) -> Type { #[allow(clippy::let_unit_value)] - let _ = Implies::::A_IMPLIES_B; + let _ = Implies::::A_IMPLIES_B; Type(self.0, self.1) } } @@ -534,10 +537,10 @@ impl<'a> Substitution<'a> { TypeArg::Type { ty } => return ty.clone().into(), TypeArg::Variable { v } => { if let Some(b) = v.bound_if_row_var() { - return Type::new_row_var_use(v.index(), b) + return Type::new_row_var_use(v.index(), b); } } - _ => () + _ => (), } panic!("Not a list of types - call validate() ?") }) @@ -584,8 +587,8 @@ pub(crate) fn check_typevar_decl( pub(crate) mod test { use super::*; - use crate::type_row; use crate::extension::prelude::USIZE_T; + use crate::type_row; #[test] fn construct() { @@ -640,13 +643,15 @@ pub(crate) mod test { } } - impl Arbitrary for super::Type { + impl Arbitrary for super::Type { type Parameters = RecursionDepth; type Strategy = BoxedStrategy; fn arbitrary_with(depth: Self::Parameters) -> Self::Strategy { // We descend here, because a TypeEnum may contain a Type any_with::(depth.descend()) - .prop_filter("Type cannot be a Row Variable", |t| RV || !matches!(t, TypeEnum::RowVariable(_,_))) + .prop_filter("Type cannot be a Row Variable", |t| { + RV || !matches!(t, TypeEnum::RowVariable(_, _)) + }) .prop_map(Self::new) .boxed() } diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index be17d8871..1ba4c599f 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -9,7 +9,7 @@ use { proptest_derive::Arbitrary, }; -use super::signature::{FuncTypeBase}; +use super::signature::FuncTypeBase; use super::type_param::{check_type_args, TypeArg, TypeParam}; use super::Substitution; @@ -43,7 +43,7 @@ impl From> for PolyFuncType { fn from(body: FuncTypeBase) -> Self { Self { params: vec![], - body + body, } } } @@ -52,7 +52,7 @@ impl From> for PolyFuncType { fn from(value: PolyFuncType) -> Self { Self { params: value.params, - body: value.body.into() + body: value.body.into(), } } } @@ -86,7 +86,7 @@ impl PolyFuncType { pub fn new(params: impl Into>, body: impl Into>) -> Self { Self { params: params.into(), - body: body.into() + body: body.into(), } } @@ -143,7 +143,7 @@ pub(crate) mod test { ExtensionRegistry::try_new([PRELUDE.to_owned(), EXTENSION.to_owned()]).unwrap(); } - impl PolyFuncType { + impl PolyFuncType { fn new_validated( params: impl Into>, body: FuncTypeBase, @@ -398,7 +398,10 @@ pub(crate) mod test { let rty = Type::new_row_var_use(0, TypeBound::Any); let pf = PolyFuncType::new_validated( [TypeParam::new_list(TP_ANY)], - FunTypeVarArgs::new(vec![USIZE_T.into(), rty.clone()], vec![Type::::new_tuple(rty)]), + FunTypeVarArgs::new( + vec![USIZE_T.into(), rty.clone()], + vec![Type::::new_tuple(rty)], + ), &PRELUDE_REGISTRY, ) .unwrap(); diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index 53ea4ea69..4e5a38a97 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -255,12 +255,12 @@ impl From for FunTypeVarArgs { Self { input: value.input.into(), output: value.output.into(), - extension_reqs: value.extension_reqs + extension_reqs: value.extension_reqs, } } } -impl PartialEq> for FuncTypeBase { +impl PartialEq> for FuncTypeBase { fn eq(&self, other: &FuncTypeBase) -> bool { self.input == other.input && self.output == other.output diff --git a/hugr-core/src/types/type_param.rs b/hugr-core/src/types/type_param.rs index 765f9f786..8e8350788 100644 --- a/hugr-core/src/types/type_param.rs +++ b/hugr-core/src/types/type_param.rs @@ -183,11 +183,11 @@ pub enum TypeArg { }, } -impl From> for TypeArg { +impl From> for TypeArg { fn from(ty: Type) -> Self { match ty.try_into_no_rv() { Ok(ty) => Self::Type { ty }, - Err((idx, bound)) => TypeArg::new_var_use(idx, TypeParam::new_list(bound)) + Err((idx, bound)) => TypeArg::new_var_use(idx, TypeParam::new_list(bound)), } } } @@ -227,7 +227,7 @@ pub struct TypeArgVariable { impl TypeArg { /// [Type::UNIT] as a [TypeArg::Type] - pub const UNIT: Self = Self::Type {ty: Type::UNIT}; + pub const UNIT: Self = Self::Type { ty: Type::UNIT }; /// Makes a TypeArg representing a use (occurrence) of the type variable /// with the specified index. @@ -303,9 +303,9 @@ impl TypeArg { } TypeArg::Sequence { elems } => { let mut are_types = elems.iter().map(|ta| match ta { - TypeArg::Type {..} => true, + TypeArg::Type { .. } => true, TypeArg::Variable { v } => v.bound_if_row_var().is_some(), - _ => false + _ => false, }); let elems = match are_types.next() { Some(true) => { @@ -346,14 +346,13 @@ impl TypeArgVariable { /// Determines whether this represents a row variable; if so, returns /// the [TypeBound] of the individual types it might stand for. pub fn bound_if_row_var(&self) -> Option { - if let TypeParam::List {param} = &self.cached_decl { - if let TypeParam::Type {b} = **param { - return Some(b) + if let TypeParam::List { param } = &self.cached_decl { + if let TypeParam::Type { b } = **param { + return Some(b); } } None } - } /// A serialized representation of a value of a [CustomType] @@ -396,8 +395,18 @@ pub fn check_type_arg(arg: &TypeArg, param: &TypeParam) -> Result<(), TypeArgErr (TypeArg::Sequence { elems }, TypeParam::List { param }) => { elems.iter().try_for_each(|arg| { // Also allow elements that are RowVars if fitting into a List of Types - if let (TypeArg::Variable { v: TypeArgVariable { idx: _, cached_decl: TypeParam::List { param: arg_var} } }, TypeParam::Type { b: param_bound }) = (arg, &**param) { - if let TypeParam::Type {b: var_bound} = **arg_var { + if let ( + TypeArg::Variable { + v: + TypeArgVariable { + idx: _, + cached_decl: TypeParam::List { param: arg_var }, + }, + }, + TypeParam::Type { b: param_bound }, + ) = (arg, &**param) + { + if let TypeParam::Type { b: var_bound } = **arg_var { if param_bound.contains(var_bound) { return Ok(()); } @@ -506,13 +515,21 @@ mod test { check(vec![], &seq_param).unwrap(); check_seq(&[rowvar(0, TypeBound::Eq)], &seq_param).unwrap(); check_seq( - &[rowvar(1, TypeBound::Any), USIZE_T.into(), rowvar(0, TypeBound::Eq)], + &[ + rowvar(1, TypeBound::Any), + USIZE_T.into(), + rowvar(0, TypeBound::Eq), + ], &TypeParam::new_list(TypeBound::Any), ) .unwrap(); // Next one fails because a list of Eq is required check_seq( - &[rowvar(1, TypeBound::Any), USIZE_T.into(), rowvar(0, TypeBound::Eq)], + &[ + rowvar(1, TypeBound::Any), + USIZE_T.into(), + rowvar(0, TypeBound::Eq), + ], &seq_param, ) .unwrap_err(); diff --git a/hugr-core/src/types/type_row.rs b/hugr-core/src/types/type_row.rs index 4c5fddcc4..b917c29fe 100644 --- a/hugr-core/src/types/type_row.rs +++ b/hugr-core/src/types/type_row.rs @@ -151,7 +151,7 @@ impl Default for TypeRow { impl From>> for TypeRow { fn from(types: Vec>) -> Self { Self { - types: types.into() + types: types.into(), } } } @@ -159,7 +159,7 @@ impl From>> for TypeRow { impl From> for TypeRow { fn from(types: Vec) -> Self { Self { - types: types.into_iter().map(Type::into_).collect() + types: types.into_iter().map(Type::into_).collect(), } } } @@ -167,7 +167,7 @@ impl From> for TypeRow { impl From for TypeRow { fn from(value: TypeRow) -> Self { Self { - types: value.iter().cloned().map(Type::into_).collect() + types: value.iter().cloned().map(Type::into_).collect(), } } } @@ -175,7 +175,7 @@ impl From for TypeRow { impl From<&'static [Type]> for TypeRow { fn from(types: &'static [Type]) -> Self { Self { - types: types.into() + types: types.into(), } } } @@ -191,7 +191,7 @@ impl From> for TypeRow { impl From for TypeRow { fn from(t: Type) -> Self { Self { - types: vec![t].into() + types: vec![t].into(), } } } @@ -214,10 +214,10 @@ impl DerefMut for TypeRow { mod test { mod proptest { use crate::proptest::RecursionDepth; - use crate::types::{TypeRow, Type}; + use crate::types::{Type, TypeRow}; use ::proptest::prelude::*; - impl Arbitrary for super::super::TypeRow { + impl Arbitrary for super::super::TypeRow { type Parameters = RecursionDepth; type Strategy = BoxedStrategy; fn arbitrary_with(depth: Self::Parameters) -> Self::Strategy { diff --git a/hugr-passes/src/const_fold.rs b/hugr-passes/src/const_fold.rs index a7afeff35..88720d41e 100644 --- a/hugr-passes/src/const_fold.rs +++ b/hugr-passes/src/const_fold.rs @@ -6,7 +6,7 @@ use hugr_core::extension::ExtensionSet; use itertools::Itertools; use thiserror::Error; -use hugr_core::hugr::{SimpleReplacementError, ValidationError}; +use hugr_core::hugr::SimpleReplacementError; use hugr_core::types::SumType; use hugr_core::Direction; use hugr_core::{ diff --git a/hugr-passes/src/merge_bbs.rs b/hugr-passes/src/merge_bbs.rs index b3132a1d8..b8a9b9daf 100644 --- a/hugr-passes/src/merge_bbs.rs +++ b/hugr-passes/src/merge_bbs.rs @@ -197,7 +197,10 @@ mod test { fn lifted_unary_unit_sum + AsRef, T>(b: &mut DFGWrapper) -> Wire { 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), [lc]) + .add_dataflow_op( + Lift::new(type_row![Type::new_unit_sum(1)], PRELUDE_ID), + [lc], + ) .unwrap(); let [w] = lift.outputs_arr(); w From d8b4f3e234d89abb1f188e7b5d6fa2c926910a98 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Wed, 12 Jun 2024 08:05:25 +0100 Subject: [PATCH 071/115] Revert change to hugr-py --- hugr-py/src/hugr/serialization/tys.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hugr-py/src/hugr/serialization/tys.py b/hugr-py/src/hugr/serialization/tys.py index fde79244e..f19e27340 100644 --- a/hugr-py/src/hugr/serialization/tys.py +++ b/hugr-py/src/hugr/serialization/tys.py @@ -353,11 +353,11 @@ class Type(RootModel): # ------------------------------------------- -# --------------- FunctionType ----------------- +# --------------- Signature ----------------- # ------------------------------------------- -class FunctionType(ConfiguredBaseModel): +class Signature(ConfiguredBaseModel): """Describes the edges required to/from a node. This includes both the concept of "signature" in the spec, and also the target From 017830e509082c2a8643a1ca3e9a75a14bf25585 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Wed, 12 Jun 2024 08:19:43 +0100 Subject: [PATCH 072/115] fix bad merge of imports --- hugr-core/src/hugr/validate/test.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/hugr-core/src/hugr/validate/test.rs b/hugr-core/src/hugr/validate/test.rs index 3e76b1b33..5bbc55027 100644 --- a/hugr-core/src/hugr/validate/test.rs +++ b/hugr-core/src/hugr/validate/test.rs @@ -953,6 +953,7 @@ fn cfg_connections() -> Result<(), Box> { #[cfg(feature = "extension_inference")] mod extension_tests { use self::ops::handle::{BasicBlockID, TailLoopID}; + use rstest::rstest; use super::*; use crate::builder::handle::Outputs; From 42c6f689720ca7a71ee853c1538475d226e2ce3e Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Wed, 12 Jun 2024 08:52:29 +0100 Subject: [PATCH 073/115] Rewrite serialize Into's for clippy --- hugr-core/src/hugr/serialize/test.rs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/hugr-core/src/hugr/serialize/test.rs b/hugr-core/src/hugr/serialize/test.rs index f949c6cb7..060c6d6dd 100644 --- a/hugr-core/src/hugr/serialize/test.rs +++ b/hugr-core/src/hugr/serialize/test.rs @@ -97,18 +97,16 @@ impl_sertesting_from!(SimpleOpDef, op_def); #[cfg(test)] impl From> for TestingModel { fn from(v: PolyFuncType) -> Self { - let mut r: Self = Default::default(); - r.poly_func_type = Some(v.into()); - r + let v: PolyFuncType = v.into(); + v.into() } } #[cfg(test)] impl From> for TestingModel { fn from(v: Type) -> Self { - let mut r: Self = Default::default(); - r.typ = Some(v.into()); - r + let t: Type = v.into(); + t.into() } } From 4f8b4acab816971cf80808391d5e2f7e7563806e Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Wed, 12 Jun 2024 09:12:52 +0100 Subject: [PATCH 074/115] Reduce change to main, and some tweaks --- hugr-core/src/builder/cfg.rs | 7 +++---- hugr-core/src/extension.rs | 7 +++---- hugr-core/src/extension/op_def.rs | 2 +- hugr-core/src/extension/type_def.rs | 3 +-- hugr-core/src/hugr/rewrite/replace.rs | 2 +- hugr-core/src/ops/constant.rs | 1 - hugr-core/src/ops/controlflow.rs | 4 ++-- hugr-core/src/ops/custom.rs | 4 ++-- hugr-core/src/ops/dataflow.rs | 12 ++++++------ hugr-core/src/ops/module.rs | 4 ++-- .../src/std_extensions/arithmetic/conversions.rs | 3 +-- hugr-core/src/std_extensions/collections.rs | 4 ++-- hugr-core/src/types/signature.rs | 2 +- 13 files changed, 25 insertions(+), 30 deletions(-) diff --git a/hugr-core/src/builder/cfg.rs b/hugr-core/src/builder/cfg.rs index f1a02024e..1ac852b45 100644 --- a/hugr-core/src/builder/cfg.rs +++ b/hugr-core/src/builder/cfg.rs @@ -5,12 +5,12 @@ use super::{ BasicBlockID, BuildError, CfgID, Container, Dataflow, HugrBuilder, Wire, }; -use crate::extension::{ExtensionRegistry, ExtensionSet}; -use crate::{hugr::views::HugrView, types::TypeRow}; +use crate::ops::{self, handle::NodeHandle, DataflowBlock, DataflowParent, ExitBlock, OpType}; use crate::{ - ops::{self, handle::NodeHandle, DataflowBlock, DataflowParent, ExitBlock, OpType}, + extension::{ExtensionRegistry, ExtensionSet}, types::FunctionType, }; +use crate::{hugr::views::HugrView, types::TypeRow}; use crate::Node; use crate::{ @@ -402,7 +402,6 @@ pub(crate) mod test { use crate::hugr::validate::InterGraphEdgeError; use crate::hugr::ValidationError; - use crate::types::FunctionType; use crate::{builder::test::NAT, type_row}; use cool_asserts::assert_matches; diff --git a/hugr-core/src/extension.rs b/hugr-core/src/extension.rs index 4c4a45c30..deecf1cbb 100644 --- a/hugr-core/src/extension.rs +++ b/hugr-core/src/extension.rs @@ -16,9 +16,8 @@ use crate::ops::constant::{ValueName, ValueNameRef}; use crate::ops::custom::{ExtensionOp, OpaqueOp}; use crate::ops::{self, OpName, OpNameRef}; use crate::types::type_param::{TypeArg, TypeArgError, TypeParam}; -use crate::types::FunctionType; -use crate::types::TypeNameRef; use crate::types::{check_typevar_decl, CustomType, Substitution, TypeBound, TypeName}; +use crate::types::{FunctionType, TypeNameRef}; mod op_def; pub use op_def::{ @@ -134,10 +133,10 @@ pub enum SignatureError { /// Invalid type arguments #[error("Invalid type arguments for operation")] InvalidTypeArgs, - /// The Extension Registry did not contain an Extension referenced by the FunctionType + /// The Extension Registry did not contain an Extension referenced by the Signature #[error("Extension '{0}' not found")] ExtensionNotFound(ExtensionId), - /// The Extension was found in the registry, but did not contain the Type(Def) referenced in the FunctionType + /// The Extension was found in the registry, but did not contain the Type(Def) referenced in the Signature #[error("Extension '{exn}' did not contain expected TypeDef '{typ}'")] ExtensionTypeNotFound { exn: ExtensionId, typ: TypeName }, /// The bound recorded for a CustomType doesn't match what the TypeDef would compute diff --git a/hugr-core/src/extension/op_def.rs b/hugr-core/src/extension/op_def.rs index afbfe6228..52e20b649 100644 --- a/hugr-core/src/extension/op_def.rs +++ b/hugr-core/src/extension/op_def.rs @@ -147,7 +147,7 @@ impl CustomValidator { } } -/// The two ways in which an OpDef may compute the FunctionType of each operation node. +/// The two ways in which an OpDef may compute the Signature of each operation node. #[derive(serde::Deserialize, serde::Serialize)] pub enum SignatureFunc { // Note: except for serialization, we could have type schemes just implement the same diff --git a/hugr-core/src/extension/type_def.rs b/hugr-core/src/extension/type_def.rs index e7fae8bca..7f03f69b3 100644 --- a/hugr-core/src/extension/type_def.rs +++ b/hugr-core/src/extension/type_def.rs @@ -189,8 +189,7 @@ mod test { .unwrap(), ); assert_eq!(typ.least_upper_bound(), TypeBound::Copyable); - let typ2: Type = - Type::new_extension(def.instantiate([TypeArg::Type { ty: USIZE_T }]).unwrap()); + let typ2: Type = Type::new_extension(def.instantiate([USIZE_T.into()]).unwrap()); assert_eq!(typ2.least_upper_bound(), TypeBound::Eq); // And some bad arguments...firstly, wrong kind of TypeArg: diff --git a/hugr-core/src/hugr/rewrite/replace.rs b/hugr-core/src/hugr/rewrite/replace.rs index 495c4a97a..9cc028053 100644 --- a/hugr-core/src/hugr/rewrite/replace.rs +++ b/hugr-core/src/hugr/rewrite/replace.rs @@ -161,7 +161,7 @@ impl Replacement { .ok_or(ReplaceError::CantReplaceRoot)?; // If no parent // Check replacement parent is of same tag. Note we do not require exact equality - // of OpType/FunctionType, e.g. to ease changing of Input/Output node signatures too. + // of OpType/Signature, e.g. to ease changing of Input/Output node signatures too. let removed = h.get_optype(parent).tag(); let replacement = self.replacement.root_type().tag(); if removed != replacement { diff --git a/hugr-core/src/ops/constant.rs b/hugr-core/src/ops/constant.rs index 66c94e192..41df9dcfe 100644 --- a/hugr-core/src/ops/constant.rs +++ b/hugr-core/src/ops/constant.rs @@ -435,7 +435,6 @@ mod test { use crate::builder::test::simple_dfg_hugr; use crate::extension::prelude::PRELUDE_ID; use crate::std_extensions::arithmetic::int_types::ConstInt; - use crate::types::FunctionType; use crate::{ builder::{BuildError, DFGBuilder, Dataflow, DataflowHugr}, extension::{ diff --git a/hugr-core/src/ops/controlflow.rs b/hugr-core/src/ops/controlflow.rs index 9f9a8e6b2..b1a6b0e37 100644 --- a/hugr-core/src/ops/controlflow.rs +++ b/hugr-core/src/ops/controlflow.rs @@ -86,7 +86,7 @@ impl DataflowOpTrait for Conditional { let mut inputs = self.other_inputs.clone(); inputs .to_mut() - .insert(0, Type::new_sum(self.sum_rows.iter().cloned())); + .insert(0, Type::new_sum(self.sum_rows.clone())); FunctionType::new(inputs, self.outputs.clone()) .with_extension_delta(self.extension_delta.clone()) } @@ -164,7 +164,7 @@ impl StaticTag for ExitBlock { impl DataflowParent for DataflowBlock { fn inner_signature(&self) -> FunctionType { // The node outputs a Sum before the data outputs of the block node - let sum_type = Type::new_sum(self.sum_rows.iter().cloned()); + let sum_type = Type::new_sum(self.sum_rows.clone()); let mut node_outputs = vec![sum_type]; node_outputs.extend_from_slice(&self.other_outputs); FunctionType::new(self.inputs.clone(), TypeRow::from(node_outputs)) diff --git a/hugr-core/src/ops/custom.rs b/hugr-core/src/ops/custom.rs index 5edf7f6c0..d97a8202c 100644 --- a/hugr-core/src/ops/custom.rs +++ b/hugr-core/src/ops/custom.rs @@ -13,8 +13,8 @@ use { use crate::extension::{ConstFoldResult, ExtensionId, ExtensionRegistry, OpDef, SignatureError}; use crate::hugr::internal::HugrMutInternals; use crate::hugr::{HugrView, NodeType}; -use crate::types::type_param::TypeArg; -use crate::types::{EdgeKind, FunctionType}; +use crate::types::EdgeKind; +use crate::types::{type_param::TypeArg, FunctionType}; use crate::{ops, Hugr, IncomingPort, Node}; use super::dataflow::DataflowOpTrait; diff --git a/hugr-core/src/ops/dataflow.rs b/hugr-core/src/ops/dataflow.rs index d52209602..4bd4362c1 100644 --- a/hugr-core/src/ops/dataflow.rs +++ b/hugr-core/src/ops/dataflow.rs @@ -111,7 +111,7 @@ impl DataflowOpTrait for Output { } // Note: We know what the input extensions should be, so we *could* give an - // instantiated FunctionType instead + // instantiated Signature instead fn signature(&self) -> FunctionType { FunctionType::new(self.types.clone(), TypeRow::new()) } @@ -158,7 +158,7 @@ impl StaticTag for T { #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[cfg_attr(test, derive(Arbitrary))] pub struct Call { - /// FunctionType of function being called + /// Signature of function being called func_sig: PolyFuncType, type_args: Vec, instantiation: FunctionType, // Cache, so we can fail in try_new() not in signature() @@ -252,7 +252,7 @@ impl Call { #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[cfg_attr(test, derive(Arbitrary))] pub struct CallIndirect { - /// FunctionType of function being called + /// Signature of function being called pub signature: FunctionType, } impl_op_name!(CallIndirect); @@ -328,7 +328,7 @@ impl LoadConstant { #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[cfg_attr(test, derive(Arbitrary))] pub struct LoadFunction { - /// FunctionType of the function + /// Signature of the function func_sig: PolyFuncType, type_args: Vec, signature: FunctionType, // Cache, so we can fail in try_new() not in signature() @@ -407,7 +407,7 @@ impl LoadFunction { /// Operations that is the parent of a dataflow graph. pub trait DataflowParent { - /// FunctionType of the inner dataflow graph. + /// Signature of the inner dataflow graph. fn inner_signature(&self) -> FunctionType; } @@ -415,7 +415,7 @@ pub trait DataflowParent { #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[cfg_attr(test, derive(Arbitrary))] pub struct DFG { - /// FunctionType of DFG node + /// Signature of DFG node pub signature: FunctionType, } diff --git a/hugr-core/src/ops/module.rs b/hugr-core/src/ops/module.rs index fba1d0609..5e97fddaf 100644 --- a/hugr-core/src/ops/module.rs +++ b/hugr-core/src/ops/module.rs @@ -44,7 +44,7 @@ pub struct FuncDefn { /// Name of function #[cfg_attr(test, proptest(strategy = "any_nonempty_string()"))] pub name: String, - /// FunctionType of the function + /// Signature of the function pub signature: PolyFuncType, } @@ -80,7 +80,7 @@ pub struct FuncDecl { /// Name of function #[cfg_attr(test, proptest(strategy = "any_nonempty_string()"))] pub name: String, - /// FunctionType of the function + /// Signature of the function pub signature: PolyFuncType, } diff --git a/hugr-core/src/std_extensions/arithmetic/conversions.rs b/hugr-core/src/std_extensions/arithmetic/conversions.rs index 9e1762e55..062233c7e 100644 --- a/hugr-core/src/std_extensions/arithmetic/conversions.rs +++ b/hugr-core/src/std_extensions/arithmetic/conversions.rs @@ -3,7 +3,6 @@ use strum_macros::{EnumIter, EnumString, IntoStaticStr}; use crate::ops::OpName; -use crate::types::{FunTypeVarArgs, Type}; use crate::{ extension::{ prelude::sum_with_error, @@ -13,7 +12,7 @@ use crate::{ }, ops::{custom::ExtensionOp, NamedOp}, type_row, - types::{PolyFuncType, TypeArg}, + types::{FunTypeVarArgs, PolyFuncType, Type, TypeArg}, Extension, }; diff --git a/hugr-core/src/std_extensions/collections.rs b/hugr-core/src/std_extensions/collections.rs index 3f7bda41a..250469960 100644 --- a/hugr-core/src/std_extensions/collections.rs +++ b/hugr-core/src/std_extensions/collections.rs @@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize}; use crate::ops::constant::ValueName; use crate::ops::{OpName, Value}; -use crate::types::{FunTypeVarArgs, TypeName}; +use crate::types::TypeName; use crate::{ extension::{ simple_op::{MakeExtensionOp, OpLoadError}, @@ -17,7 +17,7 @@ use crate::{ ops::{self, custom::ExtensionOp, NamedOp}, types::{ type_param::{TypeArg, TypeParam}, - CustomCheckFailure, CustomType, PolyFuncType, Type, TypeBound, + CustomCheckFailure, CustomType, FunTypeVarArgs, PolyFuncType, Type, TypeBound, }, utils::sorted_consts, Extension, diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index 4e5a38a97..6ea3d82d8 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -1,4 +1,4 @@ -//! Abstract and concrete FunctionType types. +//! Abstract and concrete Signature types. use itertools::Either; From 3ecc2b0d40fc50b1bc7fd864ff9bffc9aa9a94d8 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Wed, 12 Jun 2024 09:35:13 +0100 Subject: [PATCH 075/115] Accidentally deleted pub docs --- hugr-core/src/types/signature.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index 6ea3d82d8..9d37325b9 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -57,6 +57,7 @@ impl FuncTypeBase { } } + /// Create a new signature with specified inputs and outputs. pub fn new(input: impl Into>, output: impl Into>) -> Self { Self { input: input.into(), @@ -65,6 +66,8 @@ impl FuncTypeBase { } } + /// Create a new signature with the same input and output types (signature of an endomorphic + /// function). pub fn new_endo(row: impl Into>) -> Self { let row = row.into(); Self::new(row.clone(), row) From 620a96dc65156f251185ade75f5d107d02b07886 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Wed, 12 Jun 2024 09:42:31 +0100 Subject: [PATCH 076/115] Simplify check_type_arg using bound_if_row_var --- hugr-core/src/types/type_param.rs | 20 ++++++-------------- 1 file changed, 6 insertions(+), 14 deletions(-) diff --git a/hugr-core/src/types/type_param.rs b/hugr-core/src/types/type_param.rs index 8e8350788..68ea20b53 100644 --- a/hugr-core/src/types/type_param.rs +++ b/hugr-core/src/types/type_param.rs @@ -395,21 +395,13 @@ pub fn check_type_arg(arg: &TypeArg, param: &TypeParam) -> Result<(), TypeArgErr (TypeArg::Sequence { elems }, TypeParam::List { param }) => { elems.iter().try_for_each(|arg| { // Also allow elements that are RowVars if fitting into a List of Types - if let ( - TypeArg::Variable { - v: - TypeArgVariable { - idx: _, - cached_decl: TypeParam::List { param: arg_var }, - }, - }, - TypeParam::Type { b: param_bound }, - ) = (arg, &**param) + if let (TypeArg::Variable { v }, TypeParam::Type { b: param_bound }) = + (arg, &**param) { - if let TypeParam::Type { b: var_bound } = **arg_var { - if param_bound.contains(var_bound) { - return Ok(()); - } + if v.bound_if_row_var() + .is_some_and(|arg_bound| param_bound.contains(arg_bound)) + { + return Ok(()); } } check_type_arg(arg, param) From d81900876ff736cc78fa09e28ee144852bfbcf21 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Wed, 12 Jun 2024 09:44:53 +0100 Subject: [PATCH 077/115] Drop some commented-out impls in type_row.rs --- hugr-core/src/types/type_row.rs | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/hugr-core/src/types/type_row.rs b/hugr-core/src/types/type_row.rs index b917c29fe..de02e6edb 100644 --- a/hugr-core/src/types/type_row.rs +++ b/hugr-core/src/types/type_row.rs @@ -115,19 +115,6 @@ impl TypeRow { } } -/*impl From for TypeRow { - fn from(value: TypeRow) -> Self { - Self::from(value.into_owned().into_iter().map_into().collect::>>()) - } -}*/ - -/*impl Into]>> for TypeRow { - fn into(self) -> Cow<'static, [Type]> { - let tr = self.types.into_iter().cloned().map(|t| t.into()).collect(); - Cow::Owned(tr) - } -}*/ - impl TryFrom> for TypeRow { type Error = SignatureError; From 51941fdf2b7a47f3b6c3b4ff71c66b896d085c72 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Wed, 12 Jun 2024 10:30:33 +0100 Subject: [PATCH 078/115] More change reduction --- hugr-core/src/macros.rs | 4 ++-- hugr-core/src/types/signature.rs | 5 ++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/hugr-core/src/macros.rs b/hugr-core/src/macros.rs index cafb7b569..5437201ea 100644 --- a/hugr-core/src/macros.rs +++ b/hugr-core/src/macros.rs @@ -64,7 +64,7 @@ macro_rules! type_row { { use $crate::types; static ROW: &[types::Type] = &[$($t),*]; - let row: types::TypeRow = ROW.into(); + let row: types::TypeRow = ROW.into(); row } }; @@ -72,7 +72,7 @@ macro_rules! type_row { { use $crate::types; static ROW: &[types::Type] = &[$t; $n]; - let row: types::TypeRow = ROW.into(); + let row: types::TypeRow = ROW.into(); row } }; diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index 9d37325b9..b8d151608 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -273,12 +273,11 @@ impl PartialEq> for FuncType #[cfg(test)] mod test { - use crate::extension::prelude::USIZE_T; - + use crate::{extension::prelude::USIZE_T, type_row}; use super::*; #[test] fn test_function_type() { - let mut f_type = FunctionType::new(Type::::UNIT, Type::::UNIT); + let mut f_type = FunctionType::new(type_row![Type::UNIT], type_row![Type::UNIT]); assert_eq!(f_type.input_count(), 1); assert_eq!(f_type.output_count(), 1); From c173926fa1c1e902ed902a87c71fae660145b25f Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Wed, 12 Jun 2024 10:38:52 +0100 Subject: [PATCH 079/115] and more --- hugr-core/src/types/signature.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index b8d151608..af86c1775 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -274,6 +274,7 @@ impl PartialEq> for FuncType #[cfg(test)] mod test { use crate::{extension::prelude::USIZE_T, type_row}; + use super::*; #[test] fn test_function_type() { From 4e07fc0983971d5638281136fa8e87da0aef58c7 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Wed, 12 Jun 2024 10:54:04 +0100 Subject: [PATCH 080/115] correct doc --- hugr-core/src/types/signature.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index af86c1775..facda22ad 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -74,7 +74,7 @@ impl FuncTypeBase { } /// True if both inputs and outputs are necessarily empty. - /// (For [FunctionType], even after any possible substitution of row variables) + /// (For [FunTypeVarArgs], even after any possible substitution of row variables) #[inline(always)] pub fn is_empty(&self) -> bool { self.input.is_empty() && self.output.is_empty() From 49dd488e82a834828627b478d16f96b8757bfcda Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Wed, 12 Jun 2024 10:56:13 +0100 Subject: [PATCH 081/115] Fix that annoying use --- hugr-core/src/hugr/serialize/test.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/hugr-core/src/hugr/serialize/test.rs b/hugr-core/src/hugr/serialize/test.rs index 060c6d6dd..3e5495086 100644 --- a/hugr-core/src/hugr/serialize/test.rs +++ b/hugr-core/src/hugr/serialize/test.rs @@ -13,10 +13,8 @@ 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::{self, int_custom_type, ConstInt, INT_TYPES}; use crate::std_extensions::logic::NotOp; -use crate::types::{ - type_param::TypeParam, FunTypeVarArgs, FunctionType, PolyFuncType, SumType, Type, TypeArg, - TypeBound, -}; +use crate::types::type_param::TypeParam; +use crate::types::{FunTypeVarArgs, FunctionType, PolyFuncType, SumType, Type, TypeArg, TypeBound}; use crate::{type_row, OutgoingPort}; use itertools::Itertools; From 592a3c365d54f03880f8e17de0d26a3c53ec01b0 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Wed, 26 Jun 2024 11:48:02 +0100 Subject: [PATCH 082/115] remove/inline try_into_no_rv --- hugr-core/src/types.rs | 10 +--------- hugr-core/src/types/type_param.rs | 10 ++++++---- 2 files changed, 7 insertions(+), 13 deletions(-) diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index bef3a6d00..d50331822 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -478,14 +478,6 @@ impl Type { } impl Type { - fn try_into_no_rv(self) -> Result, (usize, TypeBound)> { - if let TypeEnum::RowVariable(idx, bound) = self.0 { - assert!(RV); - return Err((idx, bound)); - } - Ok(Type(self.0, self.1)) - } - /// A swiss-army-knife for any safe conversion of the const-bool "type" argument /// to/from true/false/variable. Any unsafe conversion (that might create /// a [Type]`` of a [TypeEnum::RowVariable] will fail statically with an assert. @@ -505,7 +497,7 @@ impl From> for Type { impl TryFrom> for Type { type Error = SignatureError; fn try_from(value: Type) -> Result { - value.try_into_() // .try_into_no_rv() also fine + value.try_into_() } } diff --git a/hugr-core/src/types/type_param.rs b/hugr-core/src/types/type_param.rs index 68ea20b53..f716d2418 100644 --- a/hugr-core/src/types/type_param.rs +++ b/hugr-core/src/types/type_param.rs @@ -14,7 +14,7 @@ use crate::extension::ExtensionRegistry; use crate::extension::ExtensionSet; use crate::extension::SignatureError; -use super::{check_typevar_decl, CustomType, Substitution, Type, TypeBound}; +use super::{check_typevar_decl, CustomType, Substitution, Type, TypeBound, TypeEnum}; /// The upper non-inclusive bound of a [`TypeParam::BoundedNat`] // A None inner value implies the maximum bound: u64::MAX + 1 (all u64 values valid) @@ -185,9 +185,11 @@ pub enum TypeArg { impl From> for TypeArg { fn from(ty: Type) -> Self { - match ty.try_into_no_rv() { - Ok(ty) => Self::Type { ty }, - Err((idx, bound)) => TypeArg::new_var_use(idx, TypeParam::new_list(bound)), + if let TypeEnum::RowVariable(idx, bound) = ty.0 { + assert!(RV); + TypeArg::new_var_use(idx, TypeParam::new_list(bound)) + } else { + TypeArg::Type { ty: Type(ty.0, ty.1)} } } } From edca745804f7057e39d6899b3280323fae6e59f6 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Wed, 26 Jun 2024 11:42:13 +0100 Subject: [PATCH 083/115] review: remove bogus comments and #[cfg(test)]s --- hugr-core/src/hugr/serialize/test.rs | 2 -- hugr-core/src/types.rs | 2 +- hugr-core/src/types/poly_func.rs | 3 --- hugr-core/src/types/type_param.rs | 1 - 4 files changed, 1 insertion(+), 7 deletions(-) diff --git a/hugr-core/src/hugr/serialize/test.rs b/hugr-core/src/hugr/serialize/test.rs index f107b796e..8747700b5 100644 --- a/hugr-core/src/hugr/serialize/test.rs +++ b/hugr-core/src/hugr/serialize/test.rs @@ -92,7 +92,6 @@ impl_sertesting_from!(crate::ops::Value, value); impl_sertesting_from!(NodeSer, optype); impl_sertesting_from!(SimpleOpDef, op_def); -#[cfg(test)] impl From> for TestingModel { fn from(v: PolyFuncType) -> Self { let v: PolyFuncType = v.into(); @@ -100,7 +99,6 @@ impl From> for TestingModel { } } -#[cfg(test)] impl From> for TestingModel { fn from(v: Type) -> Self { let t: Type = v.into(); diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index d50331822..266a6c7dd 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -480,7 +480,7 @@ impl Type { impl Type { /// A swiss-army-knife for any safe conversion of the const-bool "type" argument /// to/from true/false/variable. Any unsafe conversion (that might create - /// a [Type]`` of a [TypeEnum::RowVariable] will fail statically with an assert. + /// a [Type]`` of a [TypeEnum::RowVariable]) will fail statically with an assert. fn into_(self) -> Type { #[allow(clippy::let_unit_value)] let _ = Implies::::A_IMPLIES_B; diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index 1ba4c599f..006101440 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -109,9 +109,6 @@ impl PolyFuncType { /// Validates this instance, checking that the types in the body are /// wellformed with respect to the registry, and the type variables declared. - /// Allows both inputs and outputs to contain [RowVariable]s - /// - /// [RowVariable]: [crate::types::TypeEnum::RowVariable] pub fn validate(&self, reg: &ExtensionRegistry) -> Result<(), SignatureError> { // TODO https://github.com/CQCL/hugr/issues/624 validate TypeParams declared here, too self.body.validate(reg, &self.params) diff --git a/hugr-core/src/types/type_param.rs b/hugr-core/src/types/type_param.rs index f716d2418..7fdee62bb 100644 --- a/hugr-core/src/types/type_param.rs +++ b/hugr-core/src/types/type_param.rs @@ -565,7 +565,6 @@ mod test { #[test] fn type_arg_subst_row() { let row_param = TypeParam::new_list(TypeBound::Copyable); - // The here is arbitrary but we have to specify it: let row_arg: TypeArg = vec![BOOL_T.into(), TypeArg::UNIT].into(); check_type_arg(&row_arg, &row_param).unwrap(); From bc565ba5646cb0900d8f6456ad99d421ba3ae471 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Wed, 26 Jun 2024 11:54:45 +0100 Subject: [PATCH 084/115] Add TypeBase w/out default, Type is alias for TypeBase When inference had figured out that Type == Type::, we must now write TypeRV explicitly :( --- hugr-core/src/builder/dataflow.rs | 4 +- hugr-core/src/extension/op_def.rs | 4 +- hugr-core/src/extension/prelude.rs | 2 +- hugr-core/src/hugr/serialize/test.rs | 31 ++++---- hugr-core/src/hugr/validate/test.rs | 14 ++-- hugr-core/src/ops/constant.rs | 14 ++-- .../std_extensions/arithmetic/conversions.rs | 4 +- hugr-core/src/types.rs | 73 ++++++++++--------- hugr-core/src/types/poly_func.rs | 12 +-- hugr-core/src/types/serialize.rs | 18 ++--- hugr-core/src/types/signature.rs | 4 +- hugr-core/src/types/type_param.rs | 16 ++-- hugr-core/src/types/type_row.rs | 32 ++++---- 13 files changed, 118 insertions(+), 110 deletions(-) diff --git a/hugr-core/src/builder/dataflow.rs b/hugr-core/src/builder/dataflow.rs index 87a515aa5..651b308a4 100644 --- a/hugr-core/src/builder/dataflow.rs +++ b/hugr-core/src/builder/dataflow.rs @@ -212,7 +212,7 @@ pub(crate) mod test { use crate::std_extensions::logic::test::and_op; use crate::types::type_param::TypeParam; - use crate::types::{FunTypeVarArgs, FunctionType, Type, TypeBound}; + use crate::types::{FunTypeVarArgs, FunctionType, Type, TypeBound, TypeRV}; use crate::utils::test_quantum_extension::h_gate; use crate::{ builder::test::{n_identity, BIT, NAT, QB}, @@ -533,7 +533,7 @@ pub(crate) mod test { #[test] fn no_outer_row_variables() -> Result<(), BuildError> { let e = crate::hugr::validate::test::extension_with_eval_parallel(); - let tv = Type::new_row_var_use(0, TypeBound::Copyable); + let tv = TypeRV::new_row_var_use(0, TypeBound::Copyable); // Can *declare* a function that takes a function-value of unknown #args FunctionBuilder::new( "bad_eval", diff --git a/hugr-core/src/extension/op_def.rs b/hugr-core/src/extension/op_def.rs index 52e20b649..32b5b2caf 100644 --- a/hugr-core/src/extension/op_def.rs +++ b/hugr-core/src/extension/op_def.rs @@ -496,7 +496,7 @@ pub(super) mod test { use crate::ops::{CustomOp, OpName}; use crate::std_extensions::collections::{EXTENSION, LIST_TYPENAME}; use crate::types::type_param::{TypeArgError, TypeParam}; - use crate::types::{FunctionType, PolyFuncType, Type, TypeArg, TypeBound}; + use crate::types::{FunctionType, PolyFuncType, Type, TypeArg, TypeBound, TypeRV}; use crate::{const_extension_ids, Extension}; const_extension_ids! { @@ -734,7 +734,7 @@ pub(super) mod test { Ok(FunctionType::new_endo(tv)) ); // But not with an external row variable - let arg: TypeArg = Type::new_row_var_use(0, TypeBound::Eq).into(); + let arg: TypeArg = TypeRV::new_row_var_use(0, TypeBound::Eq).into(); assert_eq!( def.compute_signature(&[arg.clone()], &EMPTY_REG), Err(SignatureError::TypeArgMismatch( diff --git a/hugr-core/src/extension/prelude.rs b/hugr-core/src/extension/prelude.rs index 69f513825..acf66d7df 100644 --- a/hugr-core/src/extension/prelude.rs +++ b/hugr-core/src/extension/prelude.rs @@ -544,7 +544,7 @@ mod test { #[test] fn test_external_symbol() { let subject = ConstExternalSymbol::new("foo", Type::UNIT, false); - assert_eq!(subject.get_type(), Type::::UNIT); + assert_eq!(subject.get_type(), Type::UNIT); assert_eq!(subject.name(), "@foo"); assert!(subject.validate().is_ok()); assert_eq!( diff --git a/hugr-core/src/hugr/serialize/test.rs b/hugr-core/src/hugr/serialize/test.rs index 8747700b5..8519242bd 100644 --- a/hugr-core/src/hugr/serialize/test.rs +++ b/hugr-core/src/hugr/serialize/test.rs @@ -14,7 +14,9 @@ use crate::std_extensions::arithmetic::int_ops::INT_OPS_REGISTRY; use crate::std_extensions::arithmetic::int_types::{self, int_custom_type, ConstInt, INT_TYPES}; use crate::std_extensions::logic::NotOp; use crate::types::type_param::TypeParam; -use crate::types::{FunTypeVarArgs, FunctionType, PolyFuncType, SumType, Type, TypeArg, TypeBound}; +use crate::types::{ + FunTypeVarArgs, FunctionType, PolyFuncType, SumType, Type, TypeArg, TypeBound, TypeRV, +}; use crate::{type_row, OutgoingPort}; use itertools::Itertools; @@ -30,7 +32,7 @@ const QB: Type = crate::extension::prelude::QB_T; /// Version 1 of the Testing HUGR serialisation format, see `testing_hugr.py`. #[derive(Serialize, Deserialize, PartialEq, Debug, Default)] struct SerTestingV1 { - typ: Option>, + typ: Option, sum_type: Option, poly_func_type: Option, value: Option, @@ -85,7 +87,7 @@ macro_rules! impl_sertesting_from { }; } -impl_sertesting_from!(crate::types::Type, typ); +impl_sertesting_from!(crate::types::TypeRV, typ); impl_sertesting_from!(crate::types::SumType, sum_type); impl_sertesting_from!(crate::types::PolyFuncType, poly_func_type); impl_sertesting_from!(crate::ops::Value, value); @@ -99,9 +101,9 @@ impl From> for TestingModel { } } -impl From> for TestingModel { - fn from(v: Type) -> Self { - let t: Type = v.into(); +impl From for TestingModel { + fn from(v: Type) -> Self { + let t: TypeRV = v.into(); t.into() } } @@ -382,16 +384,15 @@ fn constants_roundtrip() -> Result<(), Box> { #[test] fn serialize_types_roundtrip() { - let g: Type = Type::new_function(FunctionType::new_endo(vec![])); - + let g = Type::new_function(FunctionType::new_endo(vec![])); check_testing_roundtrip(g.clone()); // A Simple tuple - let t: Type = Type::new_tuple(vec![USIZE_T.into(), g]); + let t = Type::new_tuple(vec![USIZE_T.into(), g]); check_testing_roundtrip(t); // A Classic sum - let t: Type = Type::new_sum([type_row![USIZE_T], type_row![FLOAT64_TYPE]]); + let t = TypeRV::new_sum([type_row![USIZE_T], type_row![FLOAT64_TYPE]]); check_testing_roundtrip(t); let t: Type = Type::new_unit_sum(4); @@ -438,11 +439,11 @@ fn polyfunctype1() -> PolyFuncType { } fn polyfunctype2() -> PolyFuncType { - let tv0 = Type::new_row_var_use(0, TypeBound::Any); - let tv1 = Type::new_row_var_use(1, TypeBound::Eq); + let tv0 = TypeRV::new_row_var_use(0, TypeBound::Any); + let tv1 = TypeRV::new_row_var_use(1, TypeBound::Eq); let params = [TypeBound::Any, TypeBound::Eq].map(TypeParam::new_list); let inputs = vec![ - Type::new_function(FunTypeVarArgs::new(tv0.clone(), tv1.clone())), + TypeRV::new_function(FunTypeVarArgs::new(tv0.clone(), tv1.clone())), tv0, ]; let res = PolyFuncType::new(params, FunTypeVarArgs::new(inputs, tv1)); @@ -461,7 +462,7 @@ fn polyfunctype2() -> PolyFuncType { #[case(PolyFuncType::new([TypeParam::Tuple { params: [TypeBound::Any.into(), TypeParam::bounded_nat(2.try_into().unwrap())].into() }], FunctionType::new_endo(type_row![])))] #[case(PolyFuncType::new( [TypeParam::new_list(TypeBound::Any)], - FunctionType::new_endo(Type::new_tuple(Type::new_row_var_use(0, TypeBound::Any)))))] + FunctionType::new_endo(Type::new_tuple(TypeRV::new_row_var_use(0, TypeBound::Any)))))] fn roundtrip_polyfunctype_fixedlen(#[case] poly_func_type: PolyFuncType) { check_testing_roundtrip(poly_func_type) } @@ -474,7 +475,7 @@ fn roundtrip_polyfunctype_fixedlen(#[case] poly_func_type: PolyFuncType) #[case(PolyFuncType::new([TypeParam::Tuple { params: [TypeBound::Any.into(), TypeParam::bounded_nat(2.try_into().unwrap())].into() }], FunctionType::new_endo(type_row![])))] #[case(PolyFuncType::new( [TypeParam::new_list(TypeBound::Any)], - FunTypeVarArgs::new_endo(Type::new_row_var_use(0, TypeBound::Any))))] + FunTypeVarArgs::new_endo(TypeRV::new_row_var_use(0, TypeBound::Any))))] #[case(polyfunctype2())] fn roundtrip_polyfunctype_varlen(#[case] poly_func_type: PolyFuncType) { check_testing_roundtrip(poly_func_type) diff --git a/hugr-core/src/hugr/validate/test.rs b/hugr-core/src/hugr/validate/test.rs index 17e51e0f6..9d088749e 100644 --- a/hugr-core/src/hugr/validate/test.rs +++ b/hugr-core/src/hugr/validate/test.rs @@ -18,7 +18,7 @@ use crate::std_extensions::logic::test::{and_op, or_op}; use crate::std_extensions::logic::{self, NotOp}; use crate::types::type_param::{TypeArg, TypeArgError}; use crate::types::{ - CustomType, FunTypeVarArgs, FunctionType, PolyFuncType, Type, TypeBound, TypeRow, + CustomType, FunTypeVarArgs, FunctionType, PolyFuncType, Type, TypeBound, TypeRV, TypeRow, }; use crate::{const_extension_ids, type_row, Direction, IncomingPort, Node}; @@ -573,16 +573,16 @@ pub(crate) fn extension_with_eval_parallel() -> Extension { let rowp = TypeParam::new_list(TypeBound::Any); let mut e = Extension::new(EXT_ID); - let inputs = Type::new_row_var_use(0, TypeBound::Any); - let outputs = Type::new_row_var_use(1, TypeBound::Any); - let evaled_fn = Type::new_function(FunTypeVarArgs::new(inputs.clone(), outputs.clone())); + let inputs = TypeRV::new_row_var_use(0, TypeBound::Any); + let outputs = TypeRV::new_row_var_use(1, TypeBound::Any); + let evaled_fn = TypeRV::new_function(FunTypeVarArgs::new(inputs.clone(), outputs.clone())); let pf = PolyFuncType::new( [rowp.clone(), rowp.clone()], FunTypeVarArgs::new(vec![evaled_fn, inputs], outputs), ); e.add_op("eval".into(), "".into(), pf).unwrap(); - let rv = |idx| Type::new_row_var_use(idx, TypeBound::Any); + let rv = |idx| TypeRV::new_row_var_use(idx, TypeBound::Any); let pf = PolyFuncType::new( [rowp.clone(), rowp.clone(), rowp.clone(), rowp.clone()], FunctionType::new( @@ -630,7 +630,7 @@ fn instantiate_row_variables() -> Result<(), Box> { Ok(()) } -fn seq1ty(t: Type) -> TypeArg { +fn seq1ty(t: TypeRV) -> TypeArg { TypeArg::Sequence { elems: vec![t.into()], } @@ -639,7 +639,7 @@ fn seq1ty(t: Type) -> TypeArg { #[test] fn row_variables() -> Result<(), Box> { let e = extension_with_eval_parallel(); - let tv = Type::new_row_var_use(0, TypeBound::Any); + let tv = TypeRV::new_row_var_use(0, TypeBound::Any); let inner_ft = Type::new_function(FunTypeVarArgs::new_endo(tv.clone())); let ft_usz = Type::new_function(FunTypeVarArgs::new_endo(vec![tv.clone(), USIZE_T.into()])); let mut fb = FunctionBuilder::new( diff --git a/hugr-core/src/ops/constant.rs b/hugr-core/src/ops/constant.rs index 82ffccb30..9bc41343f 100644 --- a/hugr-core/src/ops/constant.rs +++ b/hugr-core/src/ops/constant.rs @@ -688,14 +688,12 @@ mod test { 32, // Target around 32 total elements 3, // Each collection is up to 3 elements long |child_strat| { - (any::>(), vec(child_strat, 0..3)).prop_map( - |(typ, children)| { - Self::new(ListValue::new( - typ, - children.into_iter().map(|e| Value::Extension { e }), - )) - }, - ) + (any::(), vec(child_strat, 0..3)).prop_map(|(typ, children)| { + Self::new(ListValue::new( + typ, + children.into_iter().map(|e| Value::Extension { e }), + )) + }) }, ) .boxed() diff --git a/hugr-core/src/std_extensions/arithmetic/conversions.rs b/hugr-core/src/std_extensions/arithmetic/conversions.rs index 062233c7e..070e3b01b 100644 --- a/hugr-core/src/std_extensions/arithmetic/conversions.rs +++ b/hugr-core/src/std_extensions/arithmetic/conversions.rs @@ -12,7 +12,7 @@ use crate::{ }, ops::{custom::ExtensionOp, NamedOp}, type_row, - types::{FunTypeVarArgs, PolyFuncType, Type, TypeArg}, + types::{FunTypeVarArgs, PolyFuncType, TypeArg, TypeRV}, Extension, }; @@ -46,7 +46,7 @@ impl MakeOpDef for ConvertOpDef { match self { trunc_s | trunc_u => FunTypeVarArgs::new( type_row![FLOAT64_TYPE], - Type::::from(sum_with_error(int_tv(0))), + TypeRV::from(sum_with_error(int_tv(0))), ), convert_s | convert_u => { FunTypeVarArgs::new(vec![int_tv(0)], type_row![FLOAT64_TYPE]) diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index 266a6c7dd..1b342d64e 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -173,7 +173,7 @@ impl SumType { /// Report the tag'th variant, if it exists. pub fn get_variant(&self, tag: usize) -> Option<&TypeRow> { match self { - SumType::Unit { size } if tag < (*size as usize) => Some(Type::EMPTY_TYPEROW_REF), + SumType::Unit { size } if tag < (*size as usize) => Some(TypeRV::EMPTY_TYPEROW_REF), SumType::General { rows } => rows.get(tag), _ => None, } @@ -188,11 +188,11 @@ impl SumType { } } -impl From for Type { +impl From for TypeBase { fn from(sum: SumType) -> Self { match sum { - SumType::Unit { size } => Type::new_unit_sum(size), - SumType::General { rows } => Type::new_sum(rows), + SumType::Unit { size } => TypeBase::new_unit_sum(size), + SumType::General { rows } => TypeBase::new_sum(rows), } } } @@ -244,13 +244,13 @@ impl TypeEnum { TypeEnum::Sum(SumType::General { rows }) => least_upper_bound( rows.iter() .flat_map(TypeRow::iter) - .map(Type::least_upper_bound), + .map(TypeRV::least_upper_bound), ), } } } -struct Implies(PhantomData>, PhantomData>); +struct Implies(PhantomData>, PhantomData>); impl Implies { const A_IMPLIES_B: () = assert!(B || !A); } @@ -281,15 +281,22 @@ impl Implies { /// let func_type: Type = Type::new_function(FunctionType::new_endo(vec![])); /// assert_eq!(func_type.least_upper_bound(), TypeBound::Copyable); /// ``` -pub struct Type(TypeEnum, TypeBound); +pub struct TypeBase(TypeEnum, TypeBound); -impl PartialEq> for Type { - fn eq(&self, other: &Type) -> bool { +/// The type of a single value, that can be sent down a wire +pub type Type = TypeBase; + +/// One or more types - either a single type, or a row variable +/// standing for multiple types. +pub type TypeRV = TypeBase; + +impl PartialEq> for TypeBase { + fn eq(&self, other: &TypeBase) -> bool { self.0 == other.0 && self.1 == other.1 } } -impl Type { +impl TypeBase { /// An empty `TypeRow`. Provided here for convenience pub const EMPTY_TYPEROW: TypeRow = TypeRow::::new(); /// Unit type (empty tuple). @@ -325,7 +332,7 @@ impl Type { // TODO remove? Extensions/TypeDefs should just provide `Type` directly pub const fn new_extension(opaque: CustomType) -> Self { let bound = opaque.bound(); - Type(TypeEnum::Extension(opaque), bound) + TypeBase(TypeEnum::Extension(opaque), bound) } /// Initialize a new alias. @@ -430,16 +437,16 @@ impl Type { }; vec![ty.into_()] } - TypeEnum::Extension(cty) => vec![Type::new_extension(cty.substitute(t))], - TypeEnum::Function(bf) => vec![Type::new_function(bf.substitute(t))], + TypeEnum::Extension(cty) => vec![TypeBase::new_extension(cty.substitute(t))], + TypeEnum::Function(bf) => vec![TypeBase::new_function(bf.substitute(t))], TypeEnum::Sum(SumType::General { rows }) => { - vec![Type::new_sum(rows.iter().map(|r| r.substitute(t)))] + vec![TypeBase::new_sum(rows.iter().map(|r| r.substitute(t)))] } } } } -impl Type { +impl Type { fn substitute1(&self, s: &Substitution) -> Self { let v = self.substitute(s); let [r] = v.try_into().unwrap(); // No row vars, so every Type produces exactly one @@ -447,7 +454,7 @@ impl Type { } } -impl Type { +impl TypeRV { /// Tells if this Type is a row variable, i.e. could stand for any number >=0 of Types pub fn is_row_var(&self) -> bool { matches!(self.0, TypeEnum::RowVariable(_, _)) @@ -466,37 +473,37 @@ impl Type { } // ====== Conversions ====== -impl Type { - fn try_into_(self) -> Result, SignatureError> { +impl TypeRV { + fn try_into_(self) -> Result, SignatureError> { if !RV { if let TypeEnum::RowVariable(idx, _) = self.0 { return Err(SignatureError::RowVarWhereTypeExpected { idx }); } } - Ok(Type(self.0, self.1)) + Ok(TypeBase(self.0, self.1)) } } -impl Type { +impl TypeBase { /// A swiss-army-knife for any safe conversion of the const-bool "type" argument /// to/from true/false/variable. Any unsafe conversion (that might create - /// a [Type]`` of a [TypeEnum::RowVariable]) will fail statically with an assert. - fn into_(self) -> Type { + /// a [Type] of a [TypeEnum::RowVariable]) will fail statically with an assert. + fn into_(self) -> TypeBase { #[allow(clippy::let_unit_value)] let _ = Implies::::A_IMPLIES_B; - Type(self.0, self.1) + TypeBase(self.0, self.1) } } -impl From> for Type { - fn from(value: Type) -> Self { +impl From for TypeRV { + fn from(value: Type) -> Self { value.into_() } } -impl TryFrom> for Type { +impl TryFrom for Type { type Error = SignatureError; - fn try_from(value: Type) -> Result { + fn try_from(value: TypeRV) -> Result { value.try_into_() } } @@ -515,7 +522,7 @@ impl<'a> Substitution<'a> { arg.clone() } - fn apply_rowvar(&self, idx: usize, bound: TypeBound) -> Vec> { + fn apply_rowvar(&self, idx: usize, bound: TypeBound) -> Vec { let arg = self .0 .get(idx) @@ -529,7 +536,7 @@ impl<'a> Substitution<'a> { TypeArg::Type { ty } => return ty.clone().into(), TypeArg::Variable { v } => { if let Some(b) = v.bound_if_row_var() { - return Type::new_row_var_use(v.index(), b); + return TypeRV::new_row_var_use(v.index(), b); } } _ => (), @@ -603,14 +610,14 @@ pub(crate) mod test { #[rstest::rstest] fn sum_construct() { - let pred1: Type = Type::new_sum([type_row![], type_row![]]); - let pred2: Type = Type::new_unit_sum(2); + let pred1 = Type::new_sum([type_row![], type_row![]]); + let pred2 = TypeRV::new_unit_sum(2); assert_eq!(pred1, pred2); let pred_direct = SumType::Unit { size: 2 }; // Pick arbitrarily - assert_eq!(pred1, Type::::from(pred_direct)); + assert_eq!(pred1, Type::from(pred_direct)); } mod proptest { @@ -635,7 +642,7 @@ pub(crate) mod test { } } - impl Arbitrary for super::Type { + impl Arbitrary for super::TypeBase { type Parameters = RecursionDepth; type Strategy = BoxedStrategy; fn arbitrary_with(depth: Self::Parameters) -> Self::Strategy { diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index 006101440..91afc7c53 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -130,7 +130,9 @@ pub(crate) mod test { use crate::std_extensions::collections::{EXTENSION, LIST_TYPENAME}; use crate::types::signature::FuncTypeBase; use crate::types::type_param::{TypeArg, TypeArgError, TypeParam}; - use crate::types::{CustomType, FunTypeVarArgs, FunctionType, Type, TypeBound, TypeName}; + use crate::types::{ + CustomType, FunTypeVarArgs, FunctionType, Type, TypeBound, TypeName, TypeRV, + }; use crate::Extension; use super::PolyFuncType; @@ -368,7 +370,7 @@ pub(crate) mod test { [decl.clone()], FunTypeVarArgs::new( vec![USIZE_T], - vec![Type::new_row_var_use(0, TypeBound::Copyable)], + vec![TypeRV::new_row_var_use(0, TypeBound::Copyable)], ), &PRELUDE_REGISTRY, ) @@ -392,12 +394,12 @@ pub(crate) mod test { #[test] fn row_variables() { - let rty = Type::new_row_var_use(0, TypeBound::Any); + let rty = TypeRV::new_row_var_use(0, TypeBound::Any); let pf = PolyFuncType::new_validated( [TypeParam::new_list(TP_ANY)], FunTypeVarArgs::new( vec![USIZE_T.into(), rty.clone()], - vec![Type::::new_tuple(rty)], + vec![TypeRV::new_tuple(rty)], ), &PRELUDE_REGISTRY, ) @@ -430,7 +432,7 @@ pub(crate) mod test { #[test] fn row_variables_inner() { - let inner_fty = Type::new_function(FunTypeVarArgs::new_endo(Type::new_row_var_use( + let inner_fty = Type::new_function(FunTypeVarArgs::new_endo(TypeRV::new_row_var_use( 0, TypeBound::Copyable, ))); diff --git a/hugr-core/src/types/serialize.rs b/hugr-core/src/types/serialize.rs index 14f6f53c9..ce08e4962 100644 --- a/hugr-core/src/types/serialize.rs +++ b/hugr-core/src/types/serialize.rs @@ -1,4 +1,4 @@ -use super::{FunTypeVarArgs, SumType, Type, TypeArg, TypeBound, TypeEnum}; +use super::{FunTypeVarArgs, SumType, TypeArg, TypeBase, TypeBound, TypeEnum}; use super::custom::CustomType; @@ -20,8 +20,8 @@ pub(super) enum SerSimpleType { R { i: usize, b: TypeBound }, } -impl From> for SerSimpleType { - fn from(value: Type) -> Self { +impl From> for SerSimpleType { + fn from(value: TypeBase) -> Self { if value == QB_T { return SerSimpleType::Q; }; @@ -39,22 +39,22 @@ impl From> for SerSimpleType { } } -impl TryFrom for Type { +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::G(sig) => Type::new_function(*sig), + SerSimpleType::G(sig) => TypeBase::new_function(*sig), SerSimpleType::Sum(st) => st.into(), SerSimpleType::Array { inner, len } => { array_type(TypeArg::BoundedNat { n: len }, (*inner).try_into().unwrap()).into_() } - SerSimpleType::Opaque(o) => Type::new_extension(o), - SerSimpleType::Alias(a) => Type::new_alias(a), - SerSimpleType::V { i, b } => Type::new_var_use(i, b), + SerSimpleType::Opaque(o) => TypeBase::new_extension(o), + SerSimpleType::Alias(a) => TypeBase::new_alias(a), + SerSimpleType::V { i, b } => TypeBase::new_var_use(i, b), // We can't use new_row_var because that returns Type not Type. - SerSimpleType::R { i, b } => Type::new(TypeEnum::RowVariable(i, b)).try_into_()?, + SerSimpleType::R { i, b } => TypeBase::new(TypeEnum::RowVariable(i, b)).try_into_()?, }) } } diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index facda22ad..0884c5e2a 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -282,7 +282,7 @@ mod test { assert_eq!(f_type.input_count(), 1); assert_eq!(f_type.output_count(), 1); - assert_eq!(f_type.input_types(), &[Type::::UNIT]); + assert_eq!(f_type.input_types(), &[Type::UNIT]); assert_eq!( f_type.port_type(Port::new(Direction::Incoming, 0)), @@ -294,7 +294,7 @@ mod test { assert_eq!(f_type.port_type(out), Some(&USIZE_T)); - assert_eq!(f_type.input_types(), &[Type::::UNIT]); + assert_eq!(f_type.input_types(), &[Type::UNIT]); assert_eq!(f_type.output_types(), &[USIZE_T]); } } diff --git a/hugr-core/src/types/type_param.rs b/hugr-core/src/types/type_param.rs index 7fdee62bb..4276e7c42 100644 --- a/hugr-core/src/types/type_param.rs +++ b/hugr-core/src/types/type_param.rs @@ -14,7 +14,7 @@ use crate::extension::ExtensionRegistry; use crate::extension::ExtensionSet; use crate::extension::SignatureError; -use super::{check_typevar_decl, CustomType, Substitution, Type, TypeBound, TypeEnum}; +use super::{check_typevar_decl, CustomType, Substitution, Type, TypeBase, TypeBound, TypeEnum}; /// The upper non-inclusive bound of a [`TypeParam::BoundedNat`] // A None inner value implies the maximum bound: u64::MAX + 1 (all u64 values valid) @@ -183,13 +183,13 @@ pub enum TypeArg { }, } -impl From> for TypeArg { - fn from(ty: Type) -> Self { +impl From> for TypeArg { + fn from(ty: TypeBase) -> Self { if let TypeEnum::RowVariable(idx, bound) = ty.0 { assert!(RV); TypeArg::new_var_use(idx, TypeParam::new_list(bound)) } else { - TypeArg::Type { ty: Type(ty.0, ty.1)} + TypeArg::Type { ty: TypeBase(ty.0, ty.1)} } } } @@ -239,7 +239,7 @@ impl TypeArg { // Note a TypeParam::List of TypeParam::Type *cannot* be represented // as a TypeArg::Type because the latter stores a Type i.e. only a single type, // not a RowVariable. - TypeParam::Type { b } => Type::::new_var_use(idx, b).into(), + TypeParam::Type { b } => Type::new_var_use(idx, b).into(), // Prevent TypeArg::Variable(idx, TypeParam::Extensions) TypeParam::Extensions => TypeArg::Extensions { es: ExtensionSet::type_var(idx), @@ -482,11 +482,11 @@ mod test { use super::{check_type_arg, Substitution, TypeArg, TypeParam}; use crate::extension::prelude::{BOOL_T, PRELUDE_REGISTRY, USIZE_T}; - use crate::types::{type_param::TypeArgError, Type, TypeBound}; + use crate::types::{type_param::TypeArgError, TypeBound, TypeRV}; #[test] fn type_arg_fits_param() { - let rowvar = Type::new_row_var_use; + let rowvar = TypeRV::new_row_var_use; fn check(arg: impl Into, parm: &TypeParam) -> Result<(), TypeArgError> { check_type_arg(&arg.into(), parm) } @@ -573,7 +573,7 @@ mod test { let outer_param = TypeParam::new_list(TypeBound::Any); let outer_arg = TypeArg::Sequence { elems: vec![ - Type::new_row_var_use(0, TypeBound::Copyable).into(), + TypeRV::new_row_var_use(0, TypeBound::Copyable).into(), USIZE_T.into(), ], }; diff --git a/hugr-core/src/types/type_row.rs b/hugr-core/src/types/type_row.rs index de02e6edb..4d3201edf 100644 --- a/hugr-core/src/types/type_row.rs +++ b/hugr-core/src/types/type_row.rs @@ -7,7 +7,7 @@ use std::{ ops::{Deref, DerefMut}, }; -use super::{type_param::TypeParam, Substitution, Type}; +use super::{type_param::TypeParam, Substitution, Type, TypeBase}; use crate::{ extension::{ExtensionRegistry, SignatureError}, utils::display_list, @@ -21,7 +21,7 @@ use itertools::Itertools; #[serde(transparent)] pub struct TypeRow { /// The datatypes in the row. - types: Cow<'static, [Type]>, + types: Cow<'static, [TypeBase]>, } impl PartialEq> for TypeRow { @@ -52,12 +52,12 @@ impl TypeRow { } /// Returns a new `TypeRow` with `xs` concatenated onto `self`. - pub fn extend<'a>(&'a self, rest: impl IntoIterator>) -> Self { + pub fn extend<'a>(&'a self, rest: impl IntoIterator>) -> Self { self.iter().chain(rest).cloned().collect_vec().into() } /// Returns a reference to the types in the row. - pub fn as_slice(&self) -> &[Type] { + pub fn as_slice(&self) -> &[TypeBase] { &self.types } @@ -74,13 +74,13 @@ impl TypeRow { delegate! { to self.types { /// Iterator over the types in the row. - pub fn iter(&self) -> impl Iterator>; + pub fn iter(&self) -> impl Iterator>; /// Mutable vector of the types in the row. - pub fn to_mut(&mut self) -> &mut Vec>; + pub fn to_mut(&mut self) -> &mut Vec>; /// Allow access (consumption) of the contained elements - pub fn into_owned(self) -> Vec>; + pub fn into_owned(self) -> Vec>; /// Returns `true` if the row contains no types. pub fn is_empty(&self) -> bool ; @@ -135,8 +135,8 @@ impl Default for TypeRow { } } -impl From>> for TypeRow { - fn from(types: Vec>) -> Self { +impl From>> for TypeRow { + fn from(types: Vec>) -> Self { Self { types: types.into(), } @@ -159,16 +159,16 @@ impl From for TypeRow { } } -impl From<&'static [Type]> for TypeRow { - fn from(types: &'static [Type]) -> Self { +impl From<&'static [TypeBase]> for TypeRow { + fn from(types: &'static [TypeBase]) -> Self { Self { types: types.into(), } } } -impl From> for TypeRow { - fn from(t: Type) -> Self { +impl From> for TypeRow { + fn from(t: TypeBase) -> Self { Self { types: vec![t.into_()].into(), } @@ -184,7 +184,7 @@ impl From for TypeRow { } impl Deref for TypeRow { - type Target = [Type]; + type Target = [TypeBase]; fn deref(&self) -> &Self::Target { self.as_slice() @@ -201,7 +201,7 @@ impl DerefMut for TypeRow { mod test { mod proptest { use crate::proptest::RecursionDepth; - use crate::types::{Type, TypeRow}; + use crate::types::{TypeBase, TypeRow}; use ::proptest::prelude::*; impl Arbitrary for super::super::TypeRow { @@ -212,7 +212,7 @@ mod test { if depth.leaf() { Just(TypeRow::new()).boxed() } else { - vec(any_with::>(depth), 0..4) + vec(any_with::>(depth), 0..4) .prop_map(|ts| ts.to_vec().into()) .boxed() } From 7cebf4d027dcc1045dce4941fbcefa7bb5528c48 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Wed, 26 Jun 2024 12:18:02 +0100 Subject: [PATCH 085/115] TypeRowBase, TypeRowRV --- .../src/extension/declarative/signature.rs | 4 +- hugr-core/src/macros.rs | 2 +- .../src/std_extensions/arithmetic/int_ops.rs | 11 ++-- hugr-core/src/types.rs | 23 +++++---- hugr-core/src/types/signature.rs | 21 ++++---- hugr-core/src/types/type_param.rs | 4 +- hugr-core/src/types/type_row.rs | 51 +++++++++++-------- hugr-passes/src/const_fold/test.rs | 6 +-- 8 files changed, 68 insertions(+), 54 deletions(-) diff --git a/hugr-core/src/extension/declarative/signature.rs b/hugr-core/src/extension/declarative/signature.rs index 45047f016..867b92993 100644 --- a/hugr-core/src/extension/declarative/signature.rs +++ b/hugr-core/src/extension/declarative/signature.rs @@ -14,7 +14,7 @@ use smol_str::SmolStr; use crate::extension::prelude::PRELUDE_ID; use crate::extension::{ExtensionSet, SignatureFunc, TypeDef}; use crate::types::type_param::TypeParam; -use crate::types::{CustomType, FunTypeVarArgs, PolyFuncType, Type, TypeRow}; +use crate::types::{CustomType, FunTypeVarArgs, PolyFuncType, Type, TypeRowRV}; use crate::Extension; use super::{DeclarationContext, ExtensionDeclarationError}; @@ -41,7 +41,7 @@ impl SignatureDeclaration { op_params: &[TypeParam], ) -> Result { let make_type_row = - |v: &[SignaturePortDeclaration]| -> Result, ExtensionDeclarationError> { + |v: &[SignaturePortDeclaration]| -> Result { let types = v .iter() .map(|port_decl| port_decl.make_types(ext, ctx, op_params)) diff --git a/hugr-core/src/macros.rs b/hugr-core/src/macros.rs index 34284b014..dea66c5bc 100644 --- a/hugr-core/src/macros.rs +++ b/hugr-core/src/macros.rs @@ -57,7 +57,7 @@ pub(crate) use impl_box_clone; macro_rules! type_row { () => { { - $crate::types::TypeRow::::new() + $crate::types::TypeRow::new() } }; ($($t:expr),+ $(,)?) => { diff --git a/hugr-core/src/std_extensions/arithmetic/int_ops.rs b/hugr-core/src/std_extensions/arithmetic/int_ops.rs index 2bcedf89e..7d2c6c5ea 100644 --- a/hugr-core/src/std_extensions/arithmetic/int_ops.rs +++ b/hugr-core/src/std_extensions/arithmetic/int_ops.rs @@ -10,12 +10,13 @@ use crate::ops::custom::ExtensionOp; use crate::ops::{NamedOp, OpName}; use crate::std_extensions::arithmetic::int_types::int_type; use crate::type_row; +use crate::types::type_row::TypeRowRV; use crate::types::{FunTypeVarArgs, PolyFuncType}; use crate::utils::collect_array; use crate::{ extension::{ExtensionId, ExtensionSet, SignatureError}, - types::{type_param::TypeArg, Type, TypeRow}, + types::{type_param::TypeArg, Type}, Extension, }; @@ -127,7 +128,7 @@ impl MakeOpDef for IntOpDef { ineg | iabs | inot => iunop_sig().into(), //TODO inline idivmod_checked_u | idivmod_checked_s => { - let intpair: TypeRow = vec![int_tv(0), int_tv(1)].into(); + let intpair: TypeRowRV = vec![int_tv(0), int_tv(1)].into(); int_polytype( 2, intpair.clone(), @@ -136,7 +137,7 @@ impl MakeOpDef for IntOpDef { } .into(), idivmod_u | idivmod_s => { - let intpair: TypeRow = vec![int_tv(0), int_tv(1)].into(); + let intpair: TypeRowRV = vec![int_tv(0), int_tv(1)].into(); int_polytype(2, intpair.clone(), intpair.clone()) } .into(), @@ -232,8 +233,8 @@ impl MakeOpDef for IntOpDef { } fn int_polytype( n_vars: usize, - input: impl Into>, - output: impl Into>, + input: impl Into, + output: impl Into, ) -> PolyFuncType { PolyFuncType::new( vec![LOG_WIDTH_TYPE_PARAM; n_vars], diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index 1b342d64e..b9ef82e99 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -19,7 +19,7 @@ pub use poly_func::PolyFuncType; pub use signature::{FunTypeVarArgs, FunctionType}; use smol_str::SmolStr; pub use type_param::TypeArg; -pub use type_row::TypeRow; +pub use type_row::{TypeRow, TypeRowRV}; use itertools::FoldWhile::{Continue, Done}; use itertools::{repeat_n, Itertools}; @@ -31,6 +31,7 @@ use crate::extension::{ExtensionRegistry, SignatureError}; use crate::ops::AliasDecl; use self::type_param::TypeParam; +use self::type_row::TypeRowBase; /// A unique identifier for a type. pub type TypeName = SmolStr; @@ -131,7 +132,7 @@ pub enum SumType { Unit { size: u8 }, /// General case of a Sum type. #[allow(missing_docs)] - General { rows: Vec> }, + General { rows: Vec }, } impl std::fmt::Display for SumType { @@ -153,12 +154,12 @@ impl SumType { /// Initialize a new sum type. pub fn new(variants: impl IntoIterator) -> Self where - V: Into>, + V: Into, { let rows = variants.into_iter().map(Into::into).collect_vec(); let len: usize = rows.len(); - if len <= (u8::MAX as usize) && rows.iter().all(TypeRow::is_empty) { + if len <= (u8::MAX as usize) && rows.iter().all(TypeRowRV::is_empty) { Self::new_unary(len as u8) } else { Self::General { rows } @@ -171,7 +172,7 @@ impl SumType { } /// Report the tag'th variant, if it exists. - pub fn get_variant(&self, tag: usize) -> Option<&TypeRow> { + pub fn get_variant(&self, tag: usize) -> Option<&TypeRowRV> { match self { SumType::Unit { size } if tag < (*size as usize) => Some(TypeRV::EMPTY_TYPEROW_REF), SumType::General { rows } => rows.get(tag), @@ -243,7 +244,7 @@ impl TypeEnum { TypeEnum::Sum(SumType::Unit { size: _ }) => TypeBound::Eq, TypeEnum::Sum(SumType::General { rows }) => least_upper_bound( rows.iter() - .flat_map(TypeRow::iter) + .flat_map(TypeRowRV::iter) .map(TypeRV::least_upper_bound), ), } @@ -297,12 +298,12 @@ impl PartialEq> for TypeBase TypeBase { - /// An empty `TypeRow`. Provided here for convenience - pub const EMPTY_TYPEROW: TypeRow = TypeRow::::new(); + /// An empty `TypeRow` or `TypeRowRV`. Provided here for convenience + pub const EMPTY_TYPEROW: TypeRowBase = TypeRowBase::::new(); /// Unit type (empty tuple). pub const UNIT: Self = Self(TypeEnum::Sum(SumType::Unit { size: 1 }), TypeBound::Eq); - const EMPTY_TYPEROW_REF: &'static TypeRow = &Self::EMPTY_TYPEROW; + const EMPTY_TYPEROW_REF: &'static TypeRowBase = &Self::EMPTY_TYPEROW; /// Initialize a new function type. pub fn new_function(fun_ty: impl Into) -> Self { @@ -311,7 +312,7 @@ impl TypeBase { /// Initialize a new tuple type by providing the elements. #[inline(always)] - pub fn new_tuple(types: impl Into>) -> Self { + pub fn new_tuple(types: impl Into) -> Self { let row = types.into(); match row.len() { 0 => Self::UNIT, @@ -323,7 +324,7 @@ impl TypeBase { #[inline(always)] pub fn new_sum(variants: impl IntoIterator) -> Self where - R: Into>, + R: Into, { Self::new(TypeEnum::Sum(SumType::new(variants))) } diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index 0884c5e2a..43e3153e6 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -5,6 +5,7 @@ use itertools::Either; use std::fmt::{self, Display, Write}; use super::type_param::TypeParam; +use super::type_row::TypeRowBase; use super::{Substitution, Type, TypeBound, TypeEnum, TypeRow}; use crate::core::PortIndex; @@ -25,11 +26,11 @@ use {crate::proptest::RecursionDepth, ::proptest::prelude::*, proptest_derive::A /// [RowVariable]: crate::types::TypeEnum::RowVariable pub struct FuncTypeBase { /// Value inputs of the function. - #[cfg_attr(test, proptest(strategy = "any_with::>(params)"))] - pub input: TypeRow, + #[cfg_attr(test, proptest(strategy = "any_with::>(params)"))] + pub input: TypeRowBase, /// Value outputs of the function. - #[cfg_attr(test, proptest(strategy = "any_with::>(params)"))] - pub output: TypeRow, + #[cfg_attr(test, proptest(strategy = "any_with::>(params)"))] + pub output: TypeRowBase, /// The extension requirements which are added by the operation pub extension_reqs: ExtensionSet, } @@ -58,7 +59,7 @@ impl FuncTypeBase { } /// Create a new signature with specified inputs and outputs. - pub fn new(input: impl Into>, output: impl Into>) -> Self { + pub fn new(input: impl Into>, output: impl Into>) -> Self { Self { input: input.into(), output: output.into(), @@ -68,7 +69,7 @@ impl FuncTypeBase { /// Create a new signature with the same input and output types (signature of an endomorphic /// function). - pub fn new_endo(row: impl Into>) -> Self { + pub fn new_endo(row: impl Into>) -> Self { let row = row.into(); Self::new(row.clone(), row) } @@ -82,13 +83,13 @@ impl FuncTypeBase { #[inline] /// Returns a row of the value inputs of the function. - pub fn input(&self) -> &TypeRow { + pub fn input(&self) -> &TypeRowBase { &self.input } #[inline] /// Returns a row of the value outputs of the function. - pub fn output(&self) -> &TypeRow { + pub fn output(&self) -> &TypeRowBase { &self.output } @@ -247,8 +248,8 @@ impl TryFrom for FunctionType { type Error = SignatureError; fn try_from(value: FunTypeVarArgs) -> Result { - let input: TypeRow = value.input.try_into()?; - let output: TypeRow = value.output.try_into()?; + let input: TypeRow = value.input.try_into()?; + let output: TypeRow = value.output.try_into()?; Ok(Self::new(input, output).with_extension_delta(value.extension_reqs)) } } diff --git a/hugr-core/src/types/type_param.rs b/hugr-core/src/types/type_param.rs index 4276e7c42..7b58e234c 100644 --- a/hugr-core/src/types/type_param.rs +++ b/hugr-core/src/types/type_param.rs @@ -189,7 +189,9 @@ impl From> for TypeArg { assert!(RV); TypeArg::new_var_use(idx, TypeParam::new_list(bound)) } else { - TypeArg::Type { ty: TypeBase(ty.0, ty.1)} + TypeArg::Type { + ty: TypeBase(ty.0, ty.1), + } } } } diff --git a/hugr-core/src/types/type_row.rs b/hugr-core/src/types/type_row.rs index 4d3201edf..63008c3b4 100644 --- a/hugr-core/src/types/type_row.rs +++ b/hugr-core/src/types/type_row.rs @@ -16,16 +16,25 @@ use delegate::delegate; use itertools::Itertools; /// List of types, used for function signatures. +/// The `ROWVARS` parameter controls whether this may contain [RowVariable]s +/// +/// [RowVariable]: crate::types::TypeEnum::RowVariable #[derive(Clone, Eq, Debug, serde::Serialize, serde::Deserialize)] #[non_exhaustive] #[serde(transparent)] -pub struct TypeRow { +pub struct TypeRowBase { /// The datatypes in the row. types: Cow<'static, [TypeBase]>, } -impl PartialEq> for TypeRow { - fn eq(&self, other: &TypeRow) -> bool { +/// Row of single types i.e. of known length, for node inputs/outputs +pub type TypeRow = TypeRowBase; + +/// Row of types and/or row variables, the number of actual types is thus unknown +pub type TypeRowRV = TypeRowBase; + +impl PartialEq> for TypeRowBase { + fn eq(&self, other: &TypeRowBase) -> bool { self.types.len() == other.types.len() && self .types @@ -35,7 +44,7 @@ impl PartialEq> for TypeRow } } -impl Display for TypeRow { +impl Display for TypeRowBase { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_char('[')?; display_list(self.types.as_ref(), f)?; @@ -43,7 +52,7 @@ impl Display for TypeRow { } } -impl TypeRow { +impl TypeRowBase { /// Create a new empty row. pub const fn new() -> Self { Self { @@ -62,8 +71,8 @@ impl TypeRow { } /// Applies a substitution to the row. - /// For `TypeRow`, note this may change the length of the row. - /// For `TypeRow`, guaranteed not to change the length of the row. + /// For `TypeRowRV`, note this may change the length of the row. + /// For `TypeRow`, guaranteed not to change the length of the row. pub(super) fn substitute(&self, s: &Substitution) -> Self { self.iter() .flat_map(|ty| ty.substitute(s)) @@ -96,7 +105,7 @@ impl TypeRow { } } -impl TypeRow { +impl TypeRow { delegate! { to self.types { /// Returns the number of types in the row. @@ -115,10 +124,10 @@ impl TypeRow { } } -impl TryFrom> for TypeRow { +impl TryFrom for TypeRow { type Error = SignatureError; - fn try_from(value: TypeRow) -> Result { + fn try_from(value: TypeRowRV) -> Result { Ok(Self::from( value .into_owned() @@ -129,13 +138,13 @@ impl TryFrom> for TypeRow { } } -impl Default for TypeRow { +impl Default for TypeRowBase { fn default() -> Self { Self::new() } } -impl From>> for TypeRow { +impl From>> for TypeRowBase { fn from(types: Vec>) -> Self { Self { types: types.into(), @@ -143,7 +152,7 @@ impl From>> for TypeRow { } } -impl From> for TypeRow { +impl From> for TypeRowRV { fn from(types: Vec) -> Self { Self { types: types.into_iter().map(Type::into_).collect(), @@ -151,7 +160,7 @@ impl From> for TypeRow { } } -impl From for TypeRow { +impl From for TypeRowRV { fn from(value: TypeRow) -> Self { Self { types: value.iter().cloned().map(Type::into_).collect(), @@ -159,7 +168,7 @@ impl From for TypeRow { } } -impl From<&'static [TypeBase]> for TypeRow { +impl From<&'static [TypeBase]> for TypeRowBase { fn from(types: &'static [TypeBase]) -> Self { Self { types: types.into(), @@ -167,7 +176,7 @@ impl From<&'static [TypeBase]> for TypeRow { } } -impl From> for TypeRow { +impl From> for TypeRowRV { fn from(t: TypeBase) -> Self { Self { types: vec![t.into_()].into(), @@ -183,7 +192,7 @@ impl From for TypeRow { } } -impl Deref for TypeRow { +impl Deref for TypeRowBase { type Target = [TypeBase]; fn deref(&self) -> &Self::Target { @@ -191,7 +200,7 @@ impl Deref for TypeRow { } } -impl DerefMut for TypeRow { +impl DerefMut for TypeRowBase { fn deref_mut(&mut self) -> &mut Self::Target { self.types.to_mut() } @@ -201,16 +210,16 @@ impl DerefMut for TypeRow { mod test { mod proptest { use crate::proptest::RecursionDepth; - use crate::types::{TypeBase, TypeRow}; + use crate::types::{TypeBase, TypeRowBase}; use ::proptest::prelude::*; - impl Arbitrary for super::super::TypeRow { + impl Arbitrary for super::super::TypeRowBase { type Parameters = RecursionDepth; type Strategy = BoxedStrategy; fn arbitrary_with(depth: Self::Parameters) -> Self::Strategy { use proptest::collection::vec; if depth.leaf() { - Just(TypeRow::new()).boxed() + Just(TypeRowBase::new()).boxed() } else { vec(any_with::>(depth), 0..4) .prop_map(|ts| ts.to_vec().into()) diff --git a/hugr-passes/src/const_fold/test.rs b/hugr-passes/src/const_fold/test.rs index 27b5bbc51..258ff8617 100644 --- a/hugr-passes/src/const_fold/test.rs +++ b/hugr-passes/src/const_fold/test.rs @@ -8,7 +8,7 @@ use hugr_core::std_extensions::arithmetic::int_types::{ConstInt, INT_TYPES}; use hugr_core::std_extensions::arithmetic::{self, float_types, int_types}; use hugr_core::std_extensions::logic::{self, NaryLogic, NotOp}; use hugr_core::type_row; -use hugr_core::types::{FunctionType, Type, TypeRow}; +use hugr_core::types::{FunctionType, Type, TypeRow, TypeRowRV}; use rstest::rstest; @@ -909,7 +909,7 @@ fn test_fold_idivmod_checked_u() { // x0, x1 := int_u<5>(20), int_u<3>(0) // x2 := idivmod_checked_u(x0, x1) // output x2 == error - let intpair: TypeRow = vec![INT_TYPES[5].clone(), INT_TYPES[3].clone()].into(); + let intpair: TypeRowRV = vec![INT_TYPES[5].clone(), INT_TYPES[3].clone()].into(); let sum_type = sum_with_error(Type::new_tuple(intpair)); let mut build = DFGBuilder::new(int_fn(vec![sum_type.clone().into()])).unwrap(); let x0 = build.add_load_const(Value::extension(ConstInt::new_u(5, 20).unwrap())); @@ -979,7 +979,7 @@ fn test_fold_idivmod_checked_s() { // x0, x1 := int_s<5>(-20), int_u<3>(0) // x2 := idivmod_checked_s(x0, x1) // output x2 == error - let intpair: TypeRow = vec![INT_TYPES[5].clone(), INT_TYPES[3].clone()].into(); + let intpair: TypeRowRV = vec![INT_TYPES[5].clone(), INT_TYPES[3].clone()].into(); let sum_type = sum_with_error(Type::new_tuple(intpair)); let mut build = DFGBuilder::new(int_fn(vec![sum_type.clone().into()])).unwrap(); let x0 = build.add_load_const(Value::extension(ConstInt::new_s(5, -20).unwrap())); From 03344069d006e59b71382d5ad74699a2058b52d9 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Wed, 26 Jun 2024 12:20:54 +0100 Subject: [PATCH 086/115] FunTypeVarArgs -> FunctionTypeRV --- hugr-core/src/builder/dataflow.rs | 4 ++-- .../src/extension/declarative/signature.rs | 4 ++-- hugr-core/src/extension/op_def.rs | 8 ++++---- hugr-core/src/extension/prelude.rs | 6 +++--- hugr-core/src/hugr/serialize/test.rs | 10 +++++----- hugr-core/src/hugr/validate/test.rs | 16 ++++++++-------- .../std_extensions/arithmetic/conversions.rs | 6 +++--- .../src/std_extensions/arithmetic/int_ops.rs | 6 +++--- hugr-core/src/std_extensions/collections.rs | 6 +++--- hugr-core/src/std_extensions/logic.rs | 4 ++-- hugr-core/src/types.rs | 8 ++++---- hugr-core/src/types/poly_func.rs | 8 ++++---- hugr-core/src/types/serialize.rs | 4 ++-- hugr-core/src/types/signature.rs | 18 ++++++++++-------- hugr-core/src/utils.rs | 6 +++--- hugr/src/lib.rs | 8 ++++---- 16 files changed, 62 insertions(+), 60 deletions(-) diff --git a/hugr-core/src/builder/dataflow.rs b/hugr-core/src/builder/dataflow.rs index 651b308a4..83c9f19c4 100644 --- a/hugr-core/src/builder/dataflow.rs +++ b/hugr-core/src/builder/dataflow.rs @@ -212,7 +212,7 @@ pub(crate) mod test { use crate::std_extensions::logic::test::and_op; use crate::types::type_param::TypeParam; - use crate::types::{FunTypeVarArgs, FunctionType, Type, TypeBound, TypeRV}; + use crate::types::{FunctionType, FunctionTypeRV, Type, TypeBound, TypeRV}; use crate::utils::test_quantum_extension::h_gate; use crate::{ builder::test::{n_identity, BIT, NAT, QB}, @@ -540,7 +540,7 @@ pub(crate) mod test { PolyFuncType::new( [TypeParam::new_list(TypeBound::Copyable)], FunctionType::new( - Type::new_function(FunTypeVarArgs::new(USIZE_T, tv.clone())), + Type::new_function(FunctionTypeRV::new(USIZE_T, tv.clone())), vec![], ), ), diff --git a/hugr-core/src/extension/declarative/signature.rs b/hugr-core/src/extension/declarative/signature.rs index 867b92993..cfe80e811 100644 --- a/hugr-core/src/extension/declarative/signature.rs +++ b/hugr-core/src/extension/declarative/signature.rs @@ -14,7 +14,7 @@ use smol_str::SmolStr; use crate::extension::prelude::PRELUDE_ID; use crate::extension::{ExtensionSet, SignatureFunc, TypeDef}; use crate::types::type_param::TypeParam; -use crate::types::{CustomType, FunTypeVarArgs, PolyFuncType, Type, TypeRowRV}; +use crate::types::{CustomType, FunctionTypeRV, PolyFuncType, Type, TypeRowRV}; use crate::Extension; use super::{DeclarationContext, ExtensionDeclarationError}; @@ -50,7 +50,7 @@ impl SignatureDeclaration { Ok(types.into()) }; - let body = FunTypeVarArgs { + let body = FunctionTypeRV { input: make_type_row(&self.inputs)?, output: make_type_row(&self.outputs)?, extension_reqs: self.extensions.clone(), diff --git a/hugr-core/src/extension/op_def.rs b/hugr-core/src/extension/op_def.rs index 32b5b2caf..628e6e324 100644 --- a/hugr-core/src/extension/op_def.rs +++ b/hugr-core/src/extension/op_def.rs @@ -11,7 +11,7 @@ use super::{ use crate::ops::{OpName, OpNameRef}; use crate::types::type_param::{check_type_args, TypeArg, TypeParam}; -use crate::types::{FunTypeVarArgs, FunctionType, PolyFuncType}; +use crate::types::{FunctionType, FunctionTypeRV, PolyFuncType}; use crate::Hugr; /// Trait necessary for binary computations of OpDef signature @@ -192,15 +192,15 @@ impl From for SignatureFunc { } } -impl From for SignatureFunc { - fn from(v: FunTypeVarArgs) -> Self { +impl From for SignatureFunc { + fn from(v: FunctionTypeRV) -> Self { Self::TypeScheme(CustomValidator::from_polyfunc(v)) } } impl From for SignatureFunc { fn from(v: FunctionType) -> Self { - Self::TypeScheme(CustomValidator::from_polyfunc(FunTypeVarArgs::from(v))) + Self::TypeScheme(CustomValidator::from_polyfunc(FunctionTypeRV::from(v))) } } diff --git a/hugr-core/src/extension/prelude.rs b/hugr-core/src/extension/prelude.rs index acf66d7df..6e134c4f1 100644 --- a/hugr-core/src/extension/prelude.rs +++ b/hugr-core/src/extension/prelude.rs @@ -4,7 +4,7 @@ use lazy_static::lazy_static; use crate::ops::constant::{CustomCheckFailure, ValueName}; use crate::ops::{CustomOp, OpName}; -use crate::types::{FunTypeVarArgs, SumType, TypeName}; +use crate::types::{FunctionTypeRV, SumType, TypeName}; use crate::{ extension::{ExtensionId, TypeDefBound}, ops::constant::CustomConst, @@ -32,7 +32,7 @@ impl SignatureFromArgs for ArrayOpCustom { Ok(PolyFuncType::new( vec![TypeBound::Any.into()], - FunTypeVarArgs::new(var_arg_row, other_row), + FunctionTypeRV::new(var_arg_row, other_row), )) } @@ -67,7 +67,7 @@ impl SignatureFromArgs for GenericOpCustom { }; outs.push(ty.clone()); } - Ok(FunTypeVarArgs::new(inps, outs).into()) + Ok(FunctionTypeRV::new(inps, outs).into()) } fn static_params(&self) -> &[TypeParam] { diff --git a/hugr-core/src/hugr/serialize/test.rs b/hugr-core/src/hugr/serialize/test.rs index 8519242bd..d148365c6 100644 --- a/hugr-core/src/hugr/serialize/test.rs +++ b/hugr-core/src/hugr/serialize/test.rs @@ -15,7 +15,7 @@ use crate::std_extensions::arithmetic::int_types::{self, int_custom_type, ConstI use crate::std_extensions::logic::NotOp; use crate::types::type_param::TypeParam; use crate::types::{ - FunTypeVarArgs, FunctionType, PolyFuncType, SumType, Type, TypeArg, TypeBound, TypeRV, + FunctionType, FunctionTypeRV, PolyFuncType, SumType, Type, TypeArg, TypeBound, TypeRV, }; use crate::{type_row, OutgoingPort}; @@ -443,10 +443,10 @@ fn polyfunctype2() -> PolyFuncType { let tv1 = TypeRV::new_row_var_use(1, TypeBound::Eq); let params = [TypeBound::Any, TypeBound::Eq].map(TypeParam::new_list); let inputs = vec![ - TypeRV::new_function(FunTypeVarArgs::new(tv0.clone(), tv1.clone())), + TypeRV::new_function(FunctionTypeRV::new(tv0.clone(), tv1.clone())), tv0, ]; - let res = PolyFuncType::new(params, FunTypeVarArgs::new(inputs, tv1)); + let res = PolyFuncType::new(params, FunctionTypeRV::new(inputs, tv1)); // Just check we've got the arguments the right way round // (not that it really matters for the serialization schema we have) res.validate(&EMPTY_REG).unwrap(); @@ -468,14 +468,14 @@ fn roundtrip_polyfunctype_fixedlen(#[case] poly_func_type: PolyFuncType) } #[rstest] -#[case(FunTypeVarArgs::new_endo(type_row![]).into())] +#[case(FunctionTypeRV::new_endo(type_row![]).into())] #[case(PolyFuncType::new([TypeParam::Opaque { ty: int_custom_type(TypeArg::BoundedNat { n: 1 }) }], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Copyable)])))] #[case(PolyFuncType::new([TypeBound::Eq.into()], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Eq)])))] #[case(PolyFuncType::new([TypeParam::new_list(TypeBound::Any)], FunctionType::new_endo(type_row![])))] #[case(PolyFuncType::new([TypeParam::Tuple { params: [TypeBound::Any.into(), TypeParam::bounded_nat(2.try_into().unwrap())].into() }], FunctionType::new_endo(type_row![])))] #[case(PolyFuncType::new( [TypeParam::new_list(TypeBound::Any)], - FunTypeVarArgs::new_endo(TypeRV::new_row_var_use(0, TypeBound::Any))))] + FunctionTypeRV::new_endo(TypeRV::new_row_var_use(0, TypeBound::Any))))] #[case(polyfunctype2())] fn roundtrip_polyfunctype_varlen(#[case] poly_func_type: PolyFuncType) { check_testing_roundtrip(poly_func_type) diff --git a/hugr-core/src/hugr/validate/test.rs b/hugr-core/src/hugr/validate/test.rs index 9d088749e..411611d30 100644 --- a/hugr-core/src/hugr/validate/test.rs +++ b/hugr-core/src/hugr/validate/test.rs @@ -18,7 +18,7 @@ use crate::std_extensions::logic::test::{and_op, or_op}; use crate::std_extensions::logic::{self, NotOp}; use crate::types::type_param::{TypeArg, TypeArgError}; use crate::types::{ - CustomType, FunTypeVarArgs, FunctionType, PolyFuncType, Type, TypeBound, TypeRV, TypeRow, + CustomType, FunctionType, FunctionTypeRV, PolyFuncType, Type, TypeBound, TypeRV, TypeRow, }; use crate::{const_extension_ids, type_row, Direction, IncomingPort, Node}; @@ -575,10 +575,10 @@ pub(crate) fn extension_with_eval_parallel() -> Extension { let inputs = TypeRV::new_row_var_use(0, TypeBound::Any); let outputs = TypeRV::new_row_var_use(1, TypeBound::Any); - let evaled_fn = TypeRV::new_function(FunTypeVarArgs::new(inputs.clone(), outputs.clone())); + let evaled_fn = TypeRV::new_function(FunctionTypeRV::new(inputs.clone(), outputs.clone())); let pf = PolyFuncType::new( [rowp.clone(), rowp.clone()], - FunTypeVarArgs::new(vec![evaled_fn, inputs], outputs), + FunctionTypeRV::new(vec![evaled_fn, inputs], outputs), ); e.add_op("eval".into(), "".into(), pf).unwrap(); @@ -587,10 +587,10 @@ pub(crate) fn extension_with_eval_parallel() -> Extension { [rowp.clone(), rowp.clone(), rowp.clone(), rowp.clone()], FunctionType::new( vec![ - Type::new_function(FunTypeVarArgs::new(rv(0), rv(2))), - Type::new_function(FunTypeVarArgs::new(rv(1), rv(3))), + Type::new_function(FunctionTypeRV::new(rv(0), rv(2))), + Type::new_function(FunctionTypeRV::new(rv(1), rv(3))), ], - Type::new_function(FunTypeVarArgs::new(vec![rv(0), rv(1)], vec![rv(2), rv(3)])), + Type::new_function(FunctionTypeRV::new(vec![rv(0), rv(1)], vec![rv(2), rv(3)])), ), ); e.add_op("parallel".into(), "".into(), pf).unwrap(); @@ -640,8 +640,8 @@ fn seq1ty(t: TypeRV) -> TypeArg { 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(FunTypeVarArgs::new_endo(tv.clone())); - let ft_usz = Type::new_function(FunTypeVarArgs::new_endo(vec![tv.clone(), USIZE_T.into()])); + let inner_ft = Type::new_function(FunctionTypeRV::new_endo(tv.clone())); + let ft_usz = Type::new_function(FunctionTypeRV::new_endo(vec![tv.clone(), USIZE_T.into()])); let mut fb = FunctionBuilder::new( "id", PolyFuncType::new( diff --git a/hugr-core/src/std_extensions/arithmetic/conversions.rs b/hugr-core/src/std_extensions/arithmetic/conversions.rs index 070e3b01b..f99ae2da6 100644 --- a/hugr-core/src/std_extensions/arithmetic/conversions.rs +++ b/hugr-core/src/std_extensions/arithmetic/conversions.rs @@ -12,7 +12,7 @@ use crate::{ }, ops::{custom::ExtensionOp, NamedOp}, type_row, - types::{FunTypeVarArgs, PolyFuncType, TypeArg, TypeRV}, + types::{FunctionTypeRV, PolyFuncType, TypeArg, TypeRV}, Extension, }; @@ -44,12 +44,12 @@ impl MakeOpDef for ConvertOpDef { PolyFuncType::new( vec![LOG_WIDTH_TYPE_PARAM], match self { - trunc_s | trunc_u => FunTypeVarArgs::new( + trunc_s | trunc_u => FunctionTypeRV::new( type_row![FLOAT64_TYPE], TypeRV::from(sum_with_error(int_tv(0))), ), convert_s | convert_u => { - FunTypeVarArgs::new(vec![int_tv(0)], type_row![FLOAT64_TYPE]) + FunctionTypeRV::new(vec![int_tv(0)], type_row![FLOAT64_TYPE]) } }, ) diff --git a/hugr-core/src/std_extensions/arithmetic/int_ops.rs b/hugr-core/src/std_extensions/arithmetic/int_ops.rs index 7d2c6c5ea..43d4f5819 100644 --- a/hugr-core/src/std_extensions/arithmetic/int_ops.rs +++ b/hugr-core/src/std_extensions/arithmetic/int_ops.rs @@ -11,7 +11,7 @@ use crate::ops::{NamedOp, OpName}; use crate::std_extensions::arithmetic::int_types::int_type; use crate::type_row; use crate::types::type_row::TypeRowRV; -use crate::types::{FunTypeVarArgs, PolyFuncType}; +use crate::types::{FunctionTypeRV, PolyFuncType}; use crate::utils::collect_array; use crate::{ @@ -159,7 +159,7 @@ impl MakeOpDef for IntOpDef { } itostring_u | itostring_s => PolyFuncType::new( vec![LOG_WIDTH_TYPE_PARAM], - FunTypeVarArgs::new(vec![int_tv(0)], vec![STRING_TYPE]), + FunctionTypeRV::new(vec![int_tv(0)], vec![STRING_TYPE]), ) .into(), } @@ -238,7 +238,7 @@ fn int_polytype( ) -> PolyFuncType { PolyFuncType::new( vec![LOG_WIDTH_TYPE_PARAM; n_vars], - FunTypeVarArgs::new(input, output), + FunctionTypeRV::new(input, output), ) } diff --git a/hugr-core/src/std_extensions/collections.rs b/hugr-core/src/std_extensions/collections.rs index 250469960..745358c4f 100644 --- a/hugr-core/src/std_extensions/collections.rs +++ b/hugr-core/src/std_extensions/collections.rs @@ -17,7 +17,7 @@ use crate::{ ops::{self, custom::ExtensionOp, NamedOp}, types::{ type_param::{TypeArg, TypeParam}, - CustomCheckFailure, CustomType, FunTypeVarArgs, PolyFuncType, Type, TypeBound, + CustomCheckFailure, CustomType, FunctionTypeRV, PolyFuncType, Type, TypeBound, }, utils::sorted_consts, Extension, @@ -157,7 +157,7 @@ fn extension() -> Extension { "Pop from back of list".into(), PolyFuncType::new( vec![TP], - FunTypeVarArgs::new(vec![l.clone()], vec![l.clone(), e.clone()]), + FunctionTypeRV::new(vec![l.clone()], vec![l.clone(), e.clone()]), ), ) .unwrap() @@ -166,7 +166,7 @@ fn extension() -> Extension { .add_op( PUSH_NAME, "Push to back of list".into(), - PolyFuncType::new(vec![TP], FunTypeVarArgs::new(vec![l.clone(), e], vec![l])), + PolyFuncType::new(vec![TP], FunctionTypeRV::new(vec![l.clone(), e], vec![l])), ) .unwrap() .set_constant_folder(PushFold); diff --git a/hugr-core/src/std_extensions/logic.rs b/hugr-core/src/std_extensions/logic.rs index 6c50c9794..9bfe9aee7 100644 --- a/hugr-core/src/std_extensions/logic.rs +++ b/hugr-core/src/std_extensions/logic.rs @@ -5,7 +5,7 @@ use strum_macros::{EnumIter, EnumString, IntoStaticStr}; use crate::extension::{ConstFold, ConstFoldResult}; use crate::ops::constant::ValueName; use crate::ops::{OpName, Value}; -use crate::types::{FunTypeVarArgs, FunctionType}; +use crate::types::{FunctionType, FunctionTypeRV}; use crate::{ extension::{ prelude::BOOL_T, @@ -160,7 +160,7 @@ fn logic_op_sig() -> impl SignatureFromArgs { return Err(SignatureError::InvalidTypeArgs); }; let var_arg_row = vec![BOOL_T; n as usize]; - Ok(FunTypeVarArgs::new(var_arg_row, vec![BOOL_T]).into()) + Ok(FunctionTypeRV::new(var_arg_row, vec![BOOL_T]).into()) } fn static_params(&self) -> &[TypeParam] { diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index b9ef82e99..bfc46b0d5 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -16,7 +16,7 @@ use crate::utils::display_list_with_separator; pub use check::SumTypeError; pub use custom::CustomType; pub use poly_func::PolyFuncType; -pub use signature::{FunTypeVarArgs, FunctionType}; +pub use signature::{FunctionType, FunctionTypeRV}; use smol_str::SmolStr; pub use type_param::TypeArg; pub use type_row::{TypeRow, TypeRowRV}; @@ -216,9 +216,9 @@ pub enum TypeEnum { Function( #[cfg_attr( test, - proptest(strategy = "any_with::(params).prop_map(Box::new)") + proptest(strategy = "any_with::(params).prop_map(Box::new)") )] - Box, + Box, ), // Index into TypeParams, and cache of TypeBound (checked in validation) #[allow(missing_docs)] @@ -306,7 +306,7 @@ impl TypeBase { const EMPTY_TYPEROW_REF: &'static TypeRowBase = &Self::EMPTY_TYPEROW; /// Initialize a new function type. - pub fn new_function(fun_ty: impl Into) -> Self { + pub fn new_function(fun_ty: impl Into) -> Self { Self::new(TypeEnum::Function(Box::new(fun_ty.into()))) } diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index 91afc7c53..caa8f630d 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -131,7 +131,7 @@ pub(crate) mod test { use crate::types::signature::FuncTypeBase; use crate::types::type_param::{TypeArg, TypeArgError, TypeParam}; use crate::types::{ - CustomType, FunTypeVarArgs, FunctionType, Type, TypeBound, TypeName, TypeRV, + CustomType, FunctionType, FunctionTypeRV, Type, TypeBound, TypeName, TypeRV, }; use crate::Extension; @@ -368,7 +368,7 @@ pub(crate) mod test { }; let e = PolyFuncType::new_validated( [decl.clone()], - FunTypeVarArgs::new( + FunctionTypeRV::new( vec![USIZE_T], vec![TypeRV::new_row_var_use(0, TypeBound::Copyable)], ), @@ -397,7 +397,7 @@ pub(crate) mod test { let rty = TypeRV::new_row_var_use(0, TypeBound::Any); let pf = PolyFuncType::new_validated( [TypeParam::new_list(TP_ANY)], - FunTypeVarArgs::new( + FunctionTypeRV::new( vec![USIZE_T.into(), rty.clone()], vec![TypeRV::new_tuple(rty)], ), @@ -432,7 +432,7 @@ pub(crate) mod test { #[test] fn row_variables_inner() { - let inner_fty = Type::new_function(FunTypeVarArgs::new_endo(TypeRV::new_row_var_use( + let inner_fty = Type::new_function(FunctionTypeRV::new_endo(TypeRV::new_row_var_use( 0, TypeBound::Copyable, ))); diff --git a/hugr-core/src/types/serialize.rs b/hugr-core/src/types/serialize.rs index ce08e4962..4bae0eead 100644 --- a/hugr-core/src/types/serialize.rs +++ b/hugr-core/src/types/serialize.rs @@ -1,4 +1,4 @@ -use super::{FunTypeVarArgs, SumType, TypeArg, TypeBase, TypeBound, TypeEnum}; +use super::{FunctionTypeRV, SumType, TypeArg, TypeBase, TypeBound, TypeEnum}; use super::custom::CustomType; @@ -11,7 +11,7 @@ use crate::ops::AliasDecl; pub(super) enum SerSimpleType { Q, I, - G(Box), + G(Box), Sum(SumType), Array { inner: Box, len: u64 }, Opaque(CustomType), diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index 43e3153e6..c1f32360c 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -39,9 +39,11 @@ pub struct FuncTypeBase { /// and also the target (value) of a call (static). pub type FunctionType = FuncTypeBase; -/// A function of potentially-unknown arity; passable as a value round a Hugr -/// (see [Type::new_function]) but not a valid node type. -pub type FunTypeVarArgs = FuncTypeBase; +/// A function that may contain [RowVariable]s and thus has potentially-unknown arity; +/// passable as a value round a Hugr (see [Type::new_function]) but not a valid node type. +/// +/// [RowVariable]: crate::types::TypeEnum::RowVariable +pub type FunctionTypeRV = FuncTypeBase; impl FuncTypeBase { /// Builder method, add extension_reqs to an FunctionType @@ -75,7 +77,7 @@ impl FuncTypeBase { } /// True if both inputs and outputs are necessarily empty. - /// (For [FunTypeVarArgs], even after any possible substitution of row variables) + /// (For [FunctionTypeRV], even after any possible substitution of row variables) #[inline(always)] pub fn is_empty(&self) -> bool { self.input.is_empty() && self.output.is_empty() @@ -104,7 +106,7 @@ impl FuncTypeBase { } } -impl FunTypeVarArgs { +impl FunctionTypeRV { /// If this FunctionType contains any row variables, return one. pub fn find_rowvar(&self) -> Option<(usize, TypeBound)> { self.input @@ -244,17 +246,17 @@ impl Display for FuncTypeBase { } } -impl TryFrom for FunctionType { +impl TryFrom for FunctionType { type Error = SignatureError; - fn try_from(value: FunTypeVarArgs) -> Result { + fn try_from(value: FunctionTypeRV) -> Result { let input: TypeRow = value.input.try_into()?; let output: TypeRow = value.output.try_into()?; Ok(Self::new(input, output).with_extension_delta(value.extension_reqs)) } } -impl From for FunTypeVarArgs { +impl From for FunctionTypeRV { fn from(value: FunctionType) -> Self { Self { input: value.input.into(), diff --git a/hugr-core/src/utils.rs b/hugr-core/src/utils.rs index 96877e01b..368658faf 100644 --- a/hugr-core/src/utils.rs +++ b/hugr-core/src/utils.rs @@ -103,7 +103,7 @@ pub(crate) fn is_default(t: &T) -> bool { #[cfg(test)] pub(crate) mod test_quantum_extension { use crate::ops::{OpName, OpNameRef}; - use crate::types::FunTypeVarArgs; + use crate::types::FunctionTypeRV; use crate::{ extension::{ prelude::{BOOL_T, QB_T}, @@ -119,11 +119,11 @@ pub(crate) mod test_quantum_extension { use lazy_static::lazy_static; fn one_qb_func() -> PolyFuncType { - FunTypeVarArgs::new_endo(QB_T).into() + FunctionTypeRV::new_endo(QB_T).into() } fn two_qb_func() -> PolyFuncType { - FunTypeVarArgs::new_endo(type_row![QB_T, QB_T]).into() + FunctionTypeRV::new_endo(type_row![QB_T, QB_T]).into() } /// The extension identifier. pub const EXTENSION_ID: ExtensionId = ExtensionId::new_unchecked("test.quantum"); diff --git a/hugr/src/lib.rs b/hugr/src/lib.rs index c874d448c..aa7de4990 100644 --- a/hugr/src/lib.rs +++ b/hugr/src/lib.rs @@ -43,18 +43,18 @@ //! }, //! ops::{CustomOp, OpName}, //! type_row, -//! types::{FunTypeVarArgs, PolyFuncType}, +//! types::{FunctionTypeRV, PolyFuncType}, //! Extension, //! }; //! //! use lazy_static::lazy_static; //! //! fn one_qb_func() -> PolyFuncType { -//! FunTypeVarArgs::new_endo(type_row![QB_T]).into() +//! FunctionTypeRV::new_endo(type_row![QB_T]).into() //! } //! //! fn two_qb_func() -> PolyFuncType { -//! FunTypeVarArgs::new_endo(type_row![QB_T, QB_T]).into() +//! FunctionTypeRV::new_endo(type_row![QB_T, QB_T]).into() //! } //! /// The extension identifier. //! pub const EXTENSION_ID: ExtensionId = ExtensionId::new_unchecked("mini.quantum"); @@ -73,7 +73,7 @@ //! .add_op( //! OpName::new_inline("Measure"), //! "Measure a qubit, returning the qubit and the measurement result.".into(), -//! FunTypeVarArgs::new(type_row![QB_T], type_row![QB_T, BOOL_T]), +//! FunctionTypeRV::new(type_row![QB_T], type_row![QB_T, BOOL_T]), //! ) //! .unwrap(); //! From 00f9a40a4ce4e4807d473b9cad374437f304730c Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Wed, 26 Jun 2024 18:19:42 +0100 Subject: [PATCH 087/115] TypeScheme(,Base,RV) w/out defaults..in Rust only --- hugr-core/src/builder.rs | 4 +- hugr-core/src/builder/build_traits.rs | 4 +- hugr-core/src/builder/dataflow.rs | 6 +- hugr-core/src/builder/module.rs | 4 +- .../src/extension/declarative/signature.rs | 4 +- hugr-core/src/extension/op_def.rs | 54 ++++++++--------- hugr-core/src/extension/prelude.rs | 8 +-- hugr-core/src/hugr/serialize/test.rs | 51 ++++++++-------- hugr-core/src/hugr/validate/test.rs | 27 +++++---- hugr-core/src/hugr/views.rs | 7 +-- hugr-core/src/ops/dataflow.rs | 14 ++--- hugr-core/src/ops/module.rs | 6 +- .../std_extensions/arithmetic/conversions.rs | 4 +- .../src/std_extensions/arithmetic/int_ops.rs | 13 ++-- hugr-core/src/std_extensions/collections.rs | 6 +- hugr-core/src/std_extensions/logic.rs | 2 +- hugr-core/src/types.rs | 4 +- hugr-core/src/types/poly_func.rs | 59 ++++++++++++------- hugr-core/src/types/type_param.rs | 4 +- hugr-core/src/utils.rs | 6 +- hugr/src/lib.rs | 6 +- 21 files changed, 154 insertions(+), 139 deletions(-) diff --git a/hugr-core/src/builder.rs b/hugr-core/src/builder.rs index 9b27ffc97..68d94e305 100644 --- a/hugr-core/src/builder.rs +++ b/hugr-core/src/builder.rs @@ -223,7 +223,7 @@ pub(crate) mod test { use crate::hugr::{views::HugrView, HugrMut}; use crate::ops; use crate::std_extensions::arithmetic::float_ops::FLOAT_OPS_REGISTRY; - use crate::types::{FunctionType, PolyFuncType, Type}; + use crate::types::{FunctionType, Type, TypeScheme}; use crate::{type_row, Hugr}; use super::handle::BuildHandle; @@ -246,7 +246,7 @@ pub(crate) mod test { } pub(super) fn build_main( - signature: PolyFuncType, + signature: TypeScheme, f: impl FnOnce(FunctionBuilder<&mut Hugr>) -> Result>, BuildError>, ) -> Result { let mut module_builder = ModuleBuilder::new(); diff --git a/hugr-core/src/builder/build_traits.rs b/hugr-core/src/builder/build_traits.rs index d9409ebac..0b0fed836 100644 --- a/hugr-core/src/builder/build_traits.rs +++ b/hugr-core/src/builder/build_traits.rs @@ -19,7 +19,7 @@ use crate::{ }; use crate::extension::{ExtensionRegistry, ExtensionSet, PRELUDE_REGISTRY}; -use crate::types::{FunctionType, PolyFuncType, Type, TypeArg, TypeRow}; +use crate::types::{FunctionType, Type, TypeArg, TypeRow, TypeScheme}; use itertools::Itertools; @@ -78,7 +78,7 @@ pub trait Container { fn define_function( &mut self, name: impl Into, - signature: impl Into>, + signature: impl Into, ) -> Result, BuildError> { let signature = signature.into(); let body = signature.body().clone(); diff --git a/hugr-core/src/builder/dataflow.rs b/hugr-core/src/builder/dataflow.rs index 83c9f19c4..986cf5f4d 100644 --- a/hugr-core/src/builder/dataflow.rs +++ b/hugr-core/src/builder/dataflow.rs @@ -7,7 +7,7 @@ use std::marker::PhantomData; use crate::hugr::{HugrView, ValidationError}; use crate::ops; -use crate::types::{FunctionType, PolyFuncType}; +use crate::types::{FunctionType, TypeScheme}; use crate::extension::ExtensionRegistry; use crate::Node; @@ -140,7 +140,7 @@ impl FunctionBuilder { /// Error in adding DFG child nodes. pub fn new( name: impl Into, - signature: impl Into>, + signature: impl Into, ) -> Result { let signature = signature.into(); let body = signature.body().clone(); @@ -537,7 +537,7 @@ pub(crate) mod test { // Can *declare* a function that takes a function-value of unknown #args FunctionBuilder::new( "bad_eval", - PolyFuncType::new( + TypeScheme::new( [TypeParam::new_list(TypeBound::Copyable)], FunctionType::new( Type::new_function(FunctionTypeRV::new(USIZE_T, tv.clone())), diff --git a/hugr-core/src/builder/module.rs b/hugr-core/src/builder/module.rs index da40fdb87..d5f25dd42 100644 --- a/hugr-core/src/builder/module.rs +++ b/hugr-core/src/builder/module.rs @@ -9,7 +9,7 @@ use crate::hugr::internal::HugrMutInternals; use crate::hugr::views::HugrView; use crate::hugr::ValidationError; use crate::ops; -use crate::types::{PolyFuncType, Type, TypeBound}; +use crate::types::{Type, TypeBound, TypeScheme}; use crate::ops::handle::{AliasID, FuncID, NodeHandle}; @@ -100,7 +100,7 @@ impl + AsRef> ModuleBuilder { pub fn declare( &mut self, name: impl Into, - signature: PolyFuncType, + signature: TypeScheme, ) -> Result, BuildError> { // TODO add param names to metadata let declare_n = self.add_child_node(ops::FuncDecl { diff --git a/hugr-core/src/extension/declarative/signature.rs b/hugr-core/src/extension/declarative/signature.rs index cfe80e811..896ed7077 100644 --- a/hugr-core/src/extension/declarative/signature.rs +++ b/hugr-core/src/extension/declarative/signature.rs @@ -14,7 +14,7 @@ use smol_str::SmolStr; use crate::extension::prelude::PRELUDE_ID; use crate::extension::{ExtensionSet, SignatureFunc, TypeDef}; use crate::types::type_param::TypeParam; -use crate::types::{CustomType, FunctionTypeRV, PolyFuncType, Type, TypeRowRV}; +use crate::types::{CustomType, FunctionTypeRV, Type, TypeRowRV, TypeSchemeRV}; use crate::Extension; use super::{DeclarationContext, ExtensionDeclarationError}; @@ -56,7 +56,7 @@ impl SignatureDeclaration { extension_reqs: self.extensions.clone(), }; - let poly_func = PolyFuncType::new(op_params, body); + let poly_func = TypeSchemeRV::new(op_params, body); Ok(poly_func.into()) } } diff --git a/hugr-core/src/extension/op_def.rs b/hugr-core/src/extension/op_def.rs index 628e6e324..867792e18 100644 --- a/hugr-core/src/extension/op_def.rs +++ b/hugr-core/src/extension/op_def.rs @@ -11,7 +11,7 @@ use super::{ use crate::ops::{OpName, OpNameRef}; use crate::types::type_param::{check_type_args, TypeArg, TypeParam}; -use crate::types::{FunctionType, FunctionTypeRV, PolyFuncType}; +use crate::types::{FunctionType, FunctionTypeRV, TypeSchemeRV}; use crate::Hugr; /// Trait necessary for binary computations of OpDef signature @@ -24,7 +24,7 @@ pub trait CustomSignatureFunc: Send + Sync { arg_values: &[TypeArg], def: &'o OpDef, extension_registry: &ExtensionRegistry, - ) -> Result; + ) -> Result; /// The declared type parameters which require values in order for signature to /// be computed. fn static_params(&self) -> &[TypeParam]; @@ -34,7 +34,7 @@ pub trait CustomSignatureFunc: Send + Sync { pub trait SignatureFromArgs: Send + Sync { /// Compute signature of node given /// values for the type parameters. - fn compute_signature(&self, arg_values: &[TypeArg]) -> Result; + fn compute_signature(&self, arg_values: &[TypeArg]) -> Result; /// The declared type parameters which require values in order for signature to /// be computed. fn static_params(&self) -> &[TypeParam]; @@ -47,7 +47,7 @@ impl CustomSignatureFunc for T { arg_values: &[TypeArg], _def: &'o OpDef, _extension_registry: &ExtensionRegistry, - ) -> Result { + ) -> Result { SignatureFromArgs::compute_signature(self, arg_values) } @@ -57,7 +57,7 @@ impl CustomSignatureFunc for T { } } -/// Trait for validating type arguments to a PolyFuncType beyond conformation to +/// Trait for validating type arguments to a TypeSchemeRV beyond conformation to /// declared type parameter (which should have been checked beforehand). pub trait ValidateTypeArgs: Send + Sync { /// Validate the type arguments of node given @@ -71,7 +71,7 @@ pub trait ValidateTypeArgs: Send + Sync { ) -> Result<(), SignatureError>; } -/// Trait for validating type arguments to a PolyFuncType beyond conformation to +/// Trait for validating type arguments to a TypeSchemeRV beyond conformation to /// declared type parameter (which should have been checked beforehand), given just the arguments. pub trait ValidateJustArgs: Send + Sync { /// Validate the type arguments of node given @@ -114,30 +114,30 @@ pub trait CustomLowerFunc: Send + Sync { ) -> Option; } -/// Encode a signature as `PolyFuncType` but optionally allow validating type +/// Encode a signature as `TypeSchemeRV` but optionally allow validating type /// arguments via a custom binary. The binary cannot be serialized so will be /// lost over a serialization round-trip. #[derive(serde::Deserialize, serde::Serialize)] pub struct CustomValidator { #[serde(flatten)] - poly_func: PolyFuncType, + poly_func: TypeSchemeRV, #[serde(skip)] pub(crate) validate: Box, } impl CustomValidator { - /// Encode a signature using a `PolyFuncType` - pub fn from_polyfunc(poly_func: impl Into) -> Self { + /// Encode a signature using a `TypeSchemeRV` + pub fn from_polyfunc(poly_func: impl Into) -> Self { Self { poly_func: poly_func.into(), validate: Default::default(), } } - /// Encode a signature using a `PolyFuncType`, with a custom function for + /// Encode a signature using a `TypeSchemeRV`, with a custom function for /// validating type arguments before returning the signature. pub fn new_with_validator( - poly_func: impl Into, + poly_func: impl Into, validate: impl ValidateTypeArgs + 'static, ) -> Self { Self { @@ -186,8 +186,8 @@ impl From for SignatureFunc { } } -impl From for SignatureFunc { - fn from(v: PolyFuncType) -> Self { +impl From for SignatureFunc { + fn from(v: TypeSchemeRV) -> Self { Self::TypeScheme(CustomValidator::from_polyfunc(v)) } } @@ -235,7 +235,7 @@ impl SignatureFunc { args: &[TypeArg], exts: &ExtensionRegistry, ) -> Result { - let temp: PolyFuncType; + let temp: TypeSchemeRV; let (pf, args) = match &self { SignatureFunc::TypeScheme(custom) => { custom.validate.validate(args, def, exts)?; @@ -338,7 +338,7 @@ impl OpDef { exts: &ExtensionRegistry, var_decls: &[TypeParam], ) -> Result<(), SignatureError> { - let temp: PolyFuncType; // to keep alive + let temp: TypeSchemeRV; // to keep alive let (pf, args) = match &self.signature_func { SignatureFunc::TypeScheme(ts) => (&ts.poly_func, args), SignatureFunc::CustomFunc(custom) => { @@ -454,7 +454,7 @@ impl OpDef { impl Extension { /// Add an operation definition to the extension. Must be a type scheme - /// (defined by a [`PolyFuncType`]), a type scheme along with binary + /// (defined by a [`TypeSchemeRV`]), a type scheme along with binary /// validation for type arguments ([`CustomValidator`]), or a custom binary /// function for computing the signature given type arguments (`impl [CustomSignatureFunc]`). pub fn add_op( @@ -496,7 +496,7 @@ pub(super) mod test { use crate::ops::{CustomOp, OpName}; use crate::std_extensions::collections::{EXTENSION, LIST_TYPENAME}; use crate::types::type_param::{TypeArgError, TypeParam}; - use crate::types::{FunctionType, PolyFuncType, Type, TypeArg, TypeBound, TypeRV}; + use crate::types::{FunctionType, Type, TypeArg, TypeBound, TypeRV, TypeSchemeRV}; use crate::{const_extension_ids, Extension}; const_extension_ids! { @@ -592,7 +592,7 @@ pub(super) mod test { let list_of_var = Type::new_extension(list_def.instantiate(vec![TypeArg::new_var_use(0, TP)])?); const OP_NAME: OpName = OpName::new_inline("Reverse"); - let type_scheme = PolyFuncType::new(vec![TP], FunctionType::new_endo(vec![list_of_var])); + let type_scheme = TypeSchemeRV::new(vec![TP], FunctionType::new_endo(vec![list_of_var])); let def = e.add_op(OP_NAME, "desc".into(), type_scheme)?; def.add_lower_func(LowerFunc::FixedHugr { @@ -625,7 +625,7 @@ pub(super) mod test { #[test] fn binary_polyfunc() -> Result<(), Box> { - // Test a custom binary `compute_signature` that returns a PolyFuncType + // Test a custom binary `compute_signature` that returns a TypeSchemeRV // where the latter declares more type params itself. In particular, // we should be able to substitute (external) type variables into the latter, // but not pass them into the former (custom binary function). @@ -634,7 +634,7 @@ pub(super) mod test { fn compute_signature( &self, arg_values: &[TypeArg], - ) -> Result { + ) -> Result { const TP: TypeParam = TypeParam::Type { b: TypeBound::Any }; let [TypeArg::BoundedNat { n }] = arg_values else { return Err(SignatureError::InvalidTypeArgs); @@ -643,7 +643,7 @@ pub(super) mod test { let tvs: Vec = (0..n) .map(|_| Type::new_var_use(0, TypeBound::Any)) .collect(); - Ok(PolyFuncType::new( + Ok(TypeSchemeRV::new( vec![TP.to_owned()], FunctionType::new(tvs.clone(), vec![Type::new_tuple(tvs)]), )) @@ -714,13 +714,13 @@ pub(super) mod test { #[test] fn type_scheme_instantiate_var() -> Result<(), Box> { - // Check that we can instantiate a PolyFuncType-scheme with an (external) + // Check that we can instantiate a TypeSchemeRV-scheme with an (external) // type variable let mut e = Extension::new(EXT_ID); let def = e.add_op( "SimpleOp".into(), "".into(), - PolyFuncType::new( + TypeSchemeRV::new( vec![TypeBound::Any.into()], FunctionType::new_endo(vec![Type::new_var_use(0, TypeBound::Any)]), ), @@ -760,7 +760,7 @@ pub(super) mod test { let def = e.add_op( "SimpleOp".into(), "".into(), - PolyFuncType::new(params.clone(), fun_ty), + TypeSchemeRV::new(params.clone(), fun_ty), )?; // Concrete extension set @@ -786,7 +786,7 @@ pub(super) mod test { extension::{ op_def::LowerFunc, CustomValidator, ExtensionId, ExtensionSet, OpDef, SignatureFunc, }, - types::PolyFuncType, + types::TypeSchemeRV, }; impl Arbitrary for SignatureFunc { @@ -796,7 +796,7 @@ pub(super) mod test { // TODO there is also SignatureFunc::CustomFunc, but for now // this is not serialised. When it is, we should generate // examples here . - any::() + any::() .prop_map(|x| SignatureFunc::TypeScheme(CustomValidator::from_polyfunc(x))) .boxed() } diff --git a/hugr-core/src/extension/prelude.rs b/hugr-core/src/extension/prelude.rs index 6e134c4f1..a2917cfd0 100644 --- a/hugr-core/src/extension/prelude.rs +++ b/hugr-core/src/extension/prelude.rs @@ -11,7 +11,7 @@ use crate::{ type_row, types::{ type_param::{TypeArg, TypeParam}, - CustomType, FunctionType, PolyFuncType, Type, TypeBound, + CustomType, FunctionType, Type, TypeBound, TypeSchemeRV, }, Extension, }; @@ -21,7 +21,7 @@ struct ArrayOpCustom; const MAX: &[TypeParam; 1] = &[TypeParam::max_nat()]; impl SignatureFromArgs for ArrayOpCustom { - fn compute_signature(&self, arg_values: &[TypeArg]) -> Result { + fn compute_signature(&self, arg_values: &[TypeArg]) -> Result { let [TypeArg::BoundedNat { n }] = *arg_values else { return Err(SignatureError::InvalidTypeArgs); }; @@ -30,7 +30,7 @@ impl SignatureFromArgs for ArrayOpCustom { let var_arg_row = vec![elem_ty_var.clone(); n as usize]; let other_row = vec![array_type(TypeArg::BoundedNat { n }, elem_ty_var.clone())]; - Ok(PolyFuncType::new( + Ok(TypeSchemeRV::new( vec![TypeBound::Any.into()], FunctionTypeRV::new(var_arg_row, other_row), )) @@ -43,7 +43,7 @@ impl SignatureFromArgs for ArrayOpCustom { struct GenericOpCustom; impl SignatureFromArgs for GenericOpCustom { - fn compute_signature(&self, arg_values: &[TypeArg]) -> Result { + fn compute_signature(&self, arg_values: &[TypeArg]) -> Result { let [arg0, arg1] = arg_values else { return Err(SignatureError::InvalidTypeArgs); }; diff --git a/hugr-core/src/hugr/serialize/test.rs b/hugr-core/src/hugr/serialize/test.rs index d148365c6..d73f3d2e1 100644 --- a/hugr-core/src/hugr/serialize/test.rs +++ b/hugr-core/src/hugr/serialize/test.rs @@ -15,7 +15,8 @@ use crate::std_extensions::arithmetic::int_types::{self, int_custom_type, ConstI use crate::std_extensions::logic::NotOp; use crate::types::type_param::TypeParam; use crate::types::{ - FunctionType, FunctionTypeRV, PolyFuncType, SumType, Type, TypeArg, TypeBound, TypeRV, + FunctionType, FunctionTypeRV, SumType, Type, TypeArg, TypeBound, TypeRV, TypeScheme, + TypeSchemeRV, }; use crate::{type_row, OutgoingPort}; @@ -34,7 +35,7 @@ const QB: Type = crate::extension::prelude::QB_T; struct SerTestingV1 { typ: Option, sum_type: Option, - poly_func_type: Option, + poly_func_type: Option, value: Option, optype: Option, op_def: Option, @@ -89,14 +90,14 @@ macro_rules! impl_sertesting_from { impl_sertesting_from!(crate::types::TypeRV, typ); impl_sertesting_from!(crate::types::SumType, sum_type); -impl_sertesting_from!(crate::types::PolyFuncType, poly_func_type); +impl_sertesting_from!(crate::types::TypeSchemeRV, poly_func_type); impl_sertesting_from!(crate::ops::Value, value); impl_sertesting_from!(NodeSer, optype); impl_sertesting_from!(SimpleOpDef, op_def); -impl From> for TestingModel { - fn from(v: PolyFuncType) -> Self { - let v: PolyFuncType = v.into(); +impl From for TestingModel { + fn from(v: TypeScheme) -> Self { + let v: TypeSchemeRV = v.into(); v.into() } } @@ -388,7 +389,7 @@ fn serialize_types_roundtrip() { check_testing_roundtrip(g.clone()); // A Simple tuple - let t = Type::new_tuple(vec![USIZE_T.into(), g]); + let t = Type::new_tuple(vec![USIZE_T, g]); check_testing_roundtrip(t); // A Classic sum @@ -431,14 +432,14 @@ fn roundtrip_value(#[case] value: Value) { check_testing_roundtrip(value); } -fn polyfunctype1() -> PolyFuncType { +fn polyfunctype1() -> TypeScheme { let mut extension_set = ExtensionSet::new(); extension_set.insert_type_var(1); let function_type = FunctionType::new_endo(type_row![]).with_extension_delta(extension_set); - PolyFuncType::new([TypeParam::max_nat(), TypeParam::Extensions], function_type) + TypeScheme::new([TypeParam::max_nat(), TypeParam::Extensions], function_type) } -fn polyfunctype2() -> PolyFuncType { +fn polyfunctype2() -> TypeSchemeRV { let tv0 = TypeRV::new_row_var_use(0, TypeBound::Any); let tv1 = TypeRV::new_row_var_use(1, TypeBound::Eq); let params = [TypeBound::Any, TypeBound::Eq].map(TypeParam::new_list); @@ -446,7 +447,7 @@ fn polyfunctype2() -> PolyFuncType { TypeRV::new_function(FunctionTypeRV::new(tv0.clone(), tv1.clone())), tv0, ]; - let res = PolyFuncType::new(params, FunctionTypeRV::new(inputs, tv1)); + let res = TypeSchemeRV::new(params, FunctionTypeRV::new(inputs, tv1)); // Just check we've got the arguments the right way round // (not that it really matters for the serialization schema we have) res.validate(&EMPTY_REG).unwrap(); @@ -456,28 +457,28 @@ fn polyfunctype2() -> PolyFuncType { #[rstest] #[case(FunctionType::new_endo(type_row![]).into())] #[case(polyfunctype1())] -#[case(PolyFuncType::new([TypeParam::Opaque { ty: int_custom_type(TypeArg::BoundedNat { n: 1 }) }], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Copyable)])))] -#[case(PolyFuncType::new([TypeBound::Eq.into()], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Eq)])))] -#[case(PolyFuncType::new([TypeParam::new_list(TypeBound::Any)], FunctionType::new_endo(type_row![])))] -#[case(PolyFuncType::new([TypeParam::Tuple { params: [TypeBound::Any.into(), TypeParam::bounded_nat(2.try_into().unwrap())].into() }], FunctionType::new_endo(type_row![])))] -#[case(PolyFuncType::new( +#[case(TypeScheme::new([TypeParam::Opaque { ty: int_custom_type(TypeArg::BoundedNat { n: 1 }) }], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Copyable)])))] +#[case(TypeScheme::new([TypeBound::Eq.into()], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Eq)])))] +#[case(TypeScheme::new([TypeParam::new_list(TypeBound::Any)], FunctionType::new_endo(type_row![])))] +#[case(TypeScheme::new([TypeParam::Tuple { params: [TypeBound::Any.into(), TypeParam::bounded_nat(2.try_into().unwrap())].into() }], FunctionType::new_endo(type_row![])))] +#[case(TypeScheme::new( [TypeParam::new_list(TypeBound::Any)], FunctionType::new_endo(Type::new_tuple(TypeRV::new_row_var_use(0, TypeBound::Any)))))] -fn roundtrip_polyfunctype_fixedlen(#[case] poly_func_type: PolyFuncType) { +fn roundtrip_polyfunctype_fixedlen(#[case] poly_func_type: TypeScheme) { check_testing_roundtrip(poly_func_type) } #[rstest] #[case(FunctionTypeRV::new_endo(type_row![]).into())] -#[case(PolyFuncType::new([TypeParam::Opaque { ty: int_custom_type(TypeArg::BoundedNat { n: 1 }) }], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Copyable)])))] -#[case(PolyFuncType::new([TypeBound::Eq.into()], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Eq)])))] -#[case(PolyFuncType::new([TypeParam::new_list(TypeBound::Any)], FunctionType::new_endo(type_row![])))] -#[case(PolyFuncType::new([TypeParam::Tuple { params: [TypeBound::Any.into(), TypeParam::bounded_nat(2.try_into().unwrap())].into() }], FunctionType::new_endo(type_row![])))] -#[case(PolyFuncType::new( +#[case(TypeSchemeRV::new([TypeParam::Opaque { ty: int_custom_type(TypeArg::BoundedNat { n: 1 }) }], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Copyable)])))] +#[case(TypeSchemeRV::new([TypeBound::Eq.into()], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Eq)])))] +#[case(TypeSchemeRV::new([TypeParam::new_list(TypeBound::Any)], FunctionType::new_endo(type_row![])))] +#[case(TypeSchemeRV::new([TypeParam::Tuple { params: [TypeBound::Any.into(), TypeParam::bounded_nat(2.try_into().unwrap())].into() }], FunctionType::new_endo(type_row![])))] +#[case(TypeSchemeRV::new( [TypeParam::new_list(TypeBound::Any)], FunctionTypeRV::new_endo(TypeRV::new_row_var_use(0, TypeBound::Any))))] #[case(polyfunctype2())] -fn roundtrip_polyfunctype_varlen(#[case] poly_func_type: PolyFuncType) { +fn roundtrip_polyfunctype_varlen(#[case] poly_func_type: TypeSchemeRV) { check_testing_roundtrip(poly_func_type) } @@ -504,7 +505,7 @@ mod proptest { use super::check_testing_roundtrip; use super::{NodeSer, SimpleOpDef}; use crate::ops::{OpType, Value}; - use crate::types::{PolyFuncType, Type}; + use crate::types::{Type, TypeSchemeRV}; use proptest::prelude::*; impl Arbitrary for NodeSer { @@ -527,7 +528,7 @@ mod proptest { } #[test] - fn prop_roundtrip_poly_func_type(t: PolyFuncType) { + fn prop_roundtrip_poly_func_type(t: TypeSchemeRV) { check_testing_roundtrip(t) } diff --git a/hugr-core/src/hugr/validate/test.rs b/hugr-core/src/hugr/validate/test.rs index 411611d30..47c0b97d7 100644 --- a/hugr-core/src/hugr/validate/test.rs +++ b/hugr-core/src/hugr/validate/test.rs @@ -18,7 +18,8 @@ use crate::std_extensions::logic::test::{and_op, or_op}; use crate::std_extensions::logic::{self, NotOp}; use crate::types::type_param::{TypeArg, TypeArgError}; use crate::types::{ - CustomType, FunctionType, FunctionTypeRV, PolyFuncType, Type, TypeBound, TypeRV, TypeRow, + CustomType, FunctionType, FunctionTypeRV, Type, TypeBound, TypeRV, TypeRow, TypeScheme, + TypeSchemeRV, }; use crate::{const_extension_ids, type_row, Direction, IncomingPort, Node}; @@ -460,7 +461,7 @@ fn typevars_declared() -> Result<(), Box> { // Base case let f = FunctionBuilder::new( "myfunc", - PolyFuncType::new( + TypeScheme::new( [TypeBound::Any.into()], FunctionType::new_endo(vec![Type::new_var_use(0, TypeBound::Any)]), ), @@ -470,7 +471,7 @@ fn typevars_declared() -> Result<(), Box> { // Type refers to undeclared variable let f = FunctionBuilder::new( "myfunc", - PolyFuncType::new( + TypeScheme::new( [TypeBound::Any.into()], FunctionType::new_endo(vec![Type::new_var_use(1, TypeBound::Any)]), ), @@ -480,7 +481,7 @@ fn typevars_declared() -> Result<(), Box> { // Variable declaration incorrectly copied to use site let f = FunctionBuilder::new( "myfunc", - PolyFuncType::new( + TypeScheme::new( [TypeBound::Any.into()], FunctionType::new_endo(vec![Type::new_var_use(1, TypeBound::Copyable)]), ), @@ -498,14 +499,14 @@ fn nested_typevars() -> Result<(), Box> { fn build(t: Type) -> Result { let mut outer = FunctionBuilder::new( "outer", - PolyFuncType::new( + TypeScheme::new( [OUTER_BOUND.into()], FunctionType::new_endo(vec![Type::new_var_use(0, TypeBound::Any)]), ), )?; let inner = outer.define_function( "inner", - PolyFuncType::new([INNER_BOUND.into()], FunctionType::new_endo(vec![t])), + TypeScheme::new([INNER_BOUND.into()], FunctionType::new_endo(vec![t])), )?; let [w] = inner.input_wires_arr(); inner.finish_with_outputs([w])?; @@ -544,7 +545,7 @@ fn no_polymorphic_consts() -> Result<(), Box> { let reg = ExtensionRegistry::try_new([collections::EXTENSION.to_owned()]).unwrap(); let mut def = FunctionBuilder::new( "myfunc", - PolyFuncType::new( + TypeScheme::new( [BOUND], FunctionType::new(vec![], vec![list_of_var.clone()]) .with_extension_delta(collections::EXTENSION_NAME), @@ -576,14 +577,14 @@ pub(crate) fn extension_with_eval_parallel() -> Extension { let inputs = TypeRV::new_row_var_use(0, TypeBound::Any); let outputs = TypeRV::new_row_var_use(1, TypeBound::Any); let evaled_fn = TypeRV::new_function(FunctionTypeRV::new(inputs.clone(), outputs.clone())); - let pf = PolyFuncType::new( + let pf = TypeSchemeRV::new( [rowp.clone(), rowp.clone()], FunctionTypeRV::new(vec![evaled_fn, inputs], outputs), ); e.add_op("eval".into(), "".into(), pf).unwrap(); let rv = |idx| TypeRV::new_row_var_use(idx, TypeBound::Any); - let pf = PolyFuncType::new( + let pf = TypeSchemeRV::new( [rowp.clone(), rowp.clone(), rowp.clone(), rowp.clone()], FunctionType::new( vec![ @@ -644,7 +645,7 @@ fn row_variables() -> Result<(), Box> { let ft_usz = Type::new_function(FunctionTypeRV::new_endo(vec![tv.clone(), USIZE_T.into()])); let mut fb = FunctionBuilder::new( "id", - PolyFuncType::new( + TypeScheme::new( [TypeParam::new_list(TypeBound::Any)], FunctionType::new(inner_ft.clone(), ft_usz), ), @@ -697,7 +698,7 @@ fn test_polymorphic_call() -> Result<(), Box> { e.add_op( "eval".into(), "".into(), - PolyFuncType::new( + TypeSchemeRV::new( params.clone(), FunctionType::new( vec![evaled_fn, Type::new_var_use(0, TypeBound::Any)], @@ -725,7 +726,7 @@ fn test_polymorphic_call() -> Result<(), Box> { let es = ExtensionSet::type_var(0); let mut f = d.define_function( "two_ints", - PolyFuncType::new( + TypeScheme::new( vec![TypeParam::Extensions], FunctionType::new(vec![utou(es.clone()), int_pair.clone()], int_pair.clone()) .with_extension_delta(es.clone()), @@ -781,7 +782,7 @@ fn test_polymorphic_load() -> Result<(), Box> { let mut m = ModuleBuilder::new(); let id = m.declare( "id", - PolyFuncType::new( + TypeScheme::new( vec![TypeBound::Any.into()], FunctionType::new_endo(vec![Type::new_var_use(0, TypeBound::Any)]), ), diff --git a/hugr-core/src/hugr/views.rs b/hugr-core/src/hugr/views.rs index 29f23e8e0..fd4974f31 100644 --- a/hugr-core/src/hugr/views.rs +++ b/hugr-core/src/hugr/views.rs @@ -32,8 +32,7 @@ use crate::extension::ExtensionRegistry; use crate::ops::handle::NodeHandle; use crate::ops::{OpParent, OpTag, OpTrait, OpType}; -use crate::types::{EdgeKind, FunctionType}; -use crate::types::{PolyFuncType, Type}; +use crate::types::{EdgeKind, FunctionType, Type, TypeScheme}; use crate::{Direction, IncomingPort, Node, OutgoingPort, Port}; use itertools::Either; @@ -349,12 +348,12 @@ pub trait HugrView: HugrInternals { /// of the function. /// /// Otherwise, returns `None`. - fn get_function_type(&self) -> Option> { + fn get_function_type(&self) -> Option { let op = self.get_optype(self.root()); match op { OpType::FuncDecl(decl) => Some(decl.signature.clone()), OpType::FuncDefn(defn) => Some(defn.signature.clone()), - _ => op.inner_function_type().map(PolyFuncType::from), + _ => op.inner_function_type().map(TypeScheme::from), } } diff --git a/hugr-core/src/ops/dataflow.rs b/hugr-core/src/ops/dataflow.rs index 4bd4362c1..2f9ccfd3e 100644 --- a/hugr-core/src/ops/dataflow.rs +++ b/hugr-core/src/ops/dataflow.rs @@ -4,7 +4,7 @@ use super::{impl_op_name, OpTag, OpTrait}; use crate::extension::{ExtensionRegistry, ExtensionSet, SignatureError}; use crate::ops::StaticTag; -use crate::types::{EdgeKind, FunctionType, PolyFuncType, Type, TypeArg, TypeRow}; +use crate::types::{EdgeKind, FunctionType, Type, TypeArg, TypeRow, TypeScheme}; use crate::IncomingPort; #[cfg(test)] @@ -159,7 +159,7 @@ impl StaticTag for T { #[cfg_attr(test, derive(Arbitrary))] pub struct Call { /// Signature of function being called - func_sig: PolyFuncType, + func_sig: TypeScheme, type_args: Vec, instantiation: FunctionType, // Cache, so we can fail in try_new() not in signature() } @@ -186,7 +186,7 @@ impl Call { /// /// [TypeParam]: crate::types::type_param::TypeParam pub fn try_new( - func_sig: PolyFuncType, + func_sig: TypeScheme, type_args: impl Into>, exts: &ExtensionRegistry, ) -> Result { @@ -201,7 +201,7 @@ impl Call { #[inline] /// Return the signature of the function called by this op. - pub fn called_function_type(&self) -> &PolyFuncType { + pub fn called_function_type(&self) -> &TypeScheme { &self.func_sig } @@ -329,7 +329,7 @@ impl LoadConstant { #[cfg_attr(test, derive(Arbitrary))] pub struct LoadFunction { /// Signature of the function - func_sig: PolyFuncType, + func_sig: TypeScheme, type_args: Vec, signature: FunctionType, // Cache, so we can fail in try_new() not in signature() } @@ -355,7 +355,7 @@ impl LoadFunction { /// /// [TypeParam]: crate::types::type_param::TypeParam pub fn try_new( - func_sig: PolyFuncType, + func_sig: TypeScheme, type_args: impl Into>, exts: &ExtensionRegistry, ) -> Result { @@ -371,7 +371,7 @@ impl LoadFunction { #[inline] /// Return the type of the function loaded by this op. - pub fn function_type(&self) -> &PolyFuncType { + pub fn function_type(&self) -> &TypeScheme { &self.func_sig } diff --git a/hugr-core/src/ops/module.rs b/hugr-core/src/ops/module.rs index 5e97fddaf..0cef67227 100644 --- a/hugr-core/src/ops/module.rs +++ b/hugr-core/src/ops/module.rs @@ -7,7 +7,7 @@ use { ::proptest_derive::Arbitrary, }; -use crate::types::{EdgeKind, FunctionType, PolyFuncType}; +use crate::types::{EdgeKind, FunctionType, TypeScheme}; use crate::types::{Type, TypeBound}; use super::dataflow::DataflowParent; @@ -45,7 +45,7 @@ pub struct FuncDefn { #[cfg_attr(test, proptest(strategy = "any_nonempty_string()"))] pub name: String, /// Signature of the function - pub signature: PolyFuncType, + pub signature: TypeScheme, } impl_op_name!(FuncDefn); @@ -81,7 +81,7 @@ pub struct FuncDecl { #[cfg_attr(test, proptest(strategy = "any_nonempty_string()"))] pub name: String, /// Signature of the function - pub signature: PolyFuncType, + pub signature: TypeScheme, } impl_op_name!(FuncDecl); diff --git a/hugr-core/src/std_extensions/arithmetic/conversions.rs b/hugr-core/src/std_extensions/arithmetic/conversions.rs index f99ae2da6..743e01bed 100644 --- a/hugr-core/src/std_extensions/arithmetic/conversions.rs +++ b/hugr-core/src/std_extensions/arithmetic/conversions.rs @@ -12,7 +12,7 @@ use crate::{ }, ops::{custom::ExtensionOp, NamedOp}, type_row, - types::{FunctionTypeRV, PolyFuncType, TypeArg, TypeRV}, + types::{FunctionTypeRV, TypeArg, TypeRV, TypeSchemeRV}, Extension, }; @@ -41,7 +41,7 @@ impl MakeOpDef for ConvertOpDef { fn signature(&self) -> SignatureFunc { use ConvertOpDef::*; - PolyFuncType::new( + TypeSchemeRV::new( vec![LOG_WIDTH_TYPE_PARAM], match self { trunc_s | trunc_u => FunctionTypeRV::new( diff --git a/hugr-core/src/std_extensions/arithmetic/int_ops.rs b/hugr-core/src/std_extensions/arithmetic/int_ops.rs index 43d4f5819..b7042ba4a 100644 --- a/hugr-core/src/std_extensions/arithmetic/int_ops.rs +++ b/hugr-core/src/std_extensions/arithmetic/int_ops.rs @@ -10,8 +10,7 @@ use crate::ops::custom::ExtensionOp; use crate::ops::{NamedOp, OpName}; use crate::std_extensions::arithmetic::int_types::int_type; use crate::type_row; -use crate::types::type_row::TypeRowRV; -use crate::types::{FunctionTypeRV, PolyFuncType}; +use crate::types::{FunctionTypeRV, TypeRowRV, TypeSchemeRV}; use crate::utils::collect_array; use crate::{ @@ -157,7 +156,7 @@ impl MakeOpDef for IntOpDef { ishl | ishr | irotl | irotr => { int_polytype(2, vec![int_tv(0), int_tv(1)], vec![int_tv(0)]).into() } - itostring_u | itostring_s => PolyFuncType::new( + itostring_u | itostring_s => TypeSchemeRV::new( vec![LOG_WIDTH_TYPE_PARAM], FunctionTypeRV::new(vec![int_tv(0)], vec![STRING_TYPE]), ) @@ -235,20 +234,20 @@ fn int_polytype( n_vars: usize, input: impl Into, output: impl Into, -) -> PolyFuncType { - PolyFuncType::new( +) -> TypeSchemeRV { + TypeSchemeRV::new( vec![LOG_WIDTH_TYPE_PARAM; n_vars], FunctionTypeRV::new(input, output), ) } -fn ibinop_sig() -> PolyFuncType { +fn ibinop_sig() -> TypeSchemeRV { let int_type_var = int_tv(0); int_polytype(1, vec![int_type_var.clone(); 2], vec![int_type_var]) } -fn iunop_sig() -> PolyFuncType { +fn iunop_sig() -> TypeSchemeRV { let int_type_var = int_tv(0); int_polytype(1, vec![int_type_var.clone()], vec![int_type_var]) } diff --git a/hugr-core/src/std_extensions/collections.rs b/hugr-core/src/std_extensions/collections.rs index 745358c4f..f1a4f8319 100644 --- a/hugr-core/src/std_extensions/collections.rs +++ b/hugr-core/src/std_extensions/collections.rs @@ -17,7 +17,7 @@ use crate::{ ops::{self, custom::ExtensionOp, NamedOp}, types::{ type_param::{TypeArg, TypeParam}, - CustomCheckFailure, CustomType, FunctionTypeRV, PolyFuncType, Type, TypeBound, + CustomCheckFailure, CustomType, FunctionTypeRV, Type, TypeBound, TypeSchemeRV, }, utils::sorted_consts, Extension, @@ -155,7 +155,7 @@ fn extension() -> Extension { .add_op( POP_NAME, "Pop from back of list".into(), - PolyFuncType::new( + TypeSchemeRV::new( vec![TP], FunctionTypeRV::new(vec![l.clone()], vec![l.clone(), e.clone()]), ), @@ -166,7 +166,7 @@ fn extension() -> Extension { .add_op( PUSH_NAME, "Push to back of list".into(), - PolyFuncType::new(vec![TP], FunctionTypeRV::new(vec![l.clone(), e], vec![l])), + TypeSchemeRV::new(vec![TP], FunctionTypeRV::new(vec![l.clone(), e], vec![l])), ) .unwrap() .set_constant_folder(PushFold); diff --git a/hugr-core/src/std_extensions/logic.rs b/hugr-core/src/std_extensions/logic.rs index 9bfe9aee7..ef0a589b7 100644 --- a/hugr-core/src/std_extensions/logic.rs +++ b/hugr-core/src/std_extensions/logic.rs @@ -154,7 +154,7 @@ fn logic_op_sig() -> impl SignatureFromArgs { fn compute_signature( &self, arg_values: &[TypeArg], - ) -> Result { + ) -> Result { // get the number of input booleans. let [TypeArg::BoundedNat { n }] = *arg_values else { return Err(SignatureError::InvalidTypeArgs); diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index bfc46b0d5..53864ae7e 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -15,7 +15,7 @@ use crate::types::type_param::check_type_arg; use crate::utils::display_list_with_separator; pub use check::SumTypeError; pub use custom::CustomType; -pub use poly_func::PolyFuncType; +pub use poly_func::{TypeScheme, TypeSchemeRV}; pub use signature::{FunctionType, FunctionTypeRV}; use smol_str::SmolStr; pub use type_param::TypeArg; @@ -53,7 +53,7 @@ pub enum EdgeKind { /// /// [FuncDecl]: crate::ops::FuncDecl /// [FuncDefn]: crate::ops::FuncDefn - Function(PolyFuncType), + Function(TypeScheme), /// Explicitly enforce an ordering between nodes in a DDG. StateOrder, } diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index caa8f630d..f0a834175 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -28,7 +28,7 @@ use super::Substitution; "params.iter().map(ToString::to_string).join(\" \")", "body" )] -pub struct PolyFuncType { +pub struct TypeSchemeBase { /// The declared type parameters, i.e., these must be instantiated with /// the same number of [TypeArg]s before the function can be called. This /// defines the indices used by variables inside the body. @@ -39,7 +39,22 @@ pub struct PolyFuncType { body: FuncTypeBase, } -impl From> for PolyFuncType { +/// The polymorphic type of a [Call]-able function ([FuncDecl] or [FuncDefn]). +/// Number of inputs and outputs fixed. +/// +/// [Call]: crate::ops::Call +/// [FuncDefn]: crate::ops::FuncDefn +/// [FuncDecl]: crate::ops::FuncDecl +pub type TypeScheme = TypeSchemeBase; + +/// The polymorphic type of an [OpDef], whose number of input and outputs +/// may vary according to how [RowVariable]s therein are instantiated. +/// +/// ]OpDef]: crate::extension::OpDef +/// [RowVariable]: crate::types::TypeEnum::RowVariable +pub type TypeSchemeRV = TypeSchemeBase; + +impl From> for TypeSchemeBase { fn from(body: FuncTypeBase) -> Self { Self { params: vec![], @@ -48,8 +63,8 @@ impl From> for PolyFuncType { } } -impl From> for PolyFuncType { - fn from(value: PolyFuncType) -> Self { +impl From for TypeSchemeRV { + fn from(value: TypeScheme) -> Self { Self { params: value.params, body: value.body.into(), @@ -57,11 +72,11 @@ impl From> for PolyFuncType { } } -impl TryFrom> for FuncTypeBase { - /// If the PolyFuncType is not monomorphic, fail with its binders +impl TryFrom> for FuncTypeBase { + /// If the TypeSchemeBase is not monomorphic, fail with its binders type Error = Vec; - fn try_from(value: PolyFuncType) -> Result { + fn try_from(value: TypeSchemeBase) -> Result { if value.params.is_empty() { Ok(value.body) } else { @@ -70,7 +85,7 @@ impl TryFrom> for FuncTypeBase { } } -impl PolyFuncType { +impl TypeSchemeBase { /// The type parameters, aka binders, over which this type is polymorphic pub fn params(&self) -> &[TypeParam] { &self.params @@ -81,7 +96,7 @@ impl PolyFuncType { &self.body } - /// Create a new PolyFuncType given the kinds of the variables it declares + /// Create a new TypeSchemeBase given the kinds of the variables it declares /// and the underlying function type. pub fn new(params: impl Into>, body: impl Into>) -> Self { Self { @@ -90,7 +105,7 @@ impl PolyFuncType { } } - /// Instantiates an outer [PolyFuncType], i.e. with no free variables + /// Instantiates an outer [TypeSchemeBase], i.e. with no free variables /// (as ensured by [Self::validate]), into a monomorphic type. /// /// # Errors @@ -135,14 +150,14 @@ pub(crate) mod test { }; use crate::Extension; - use super::PolyFuncType; + use super::TypeSchemeBase; lazy_static! { static ref REGISTRY: ExtensionRegistry = ExtensionRegistry::try_new([PRELUDE.to_owned(), EXTENSION.to_owned()]).unwrap(); } - impl PolyFuncType { + impl TypeSchemeBase { fn new_validated( params: impl Into>, body: FuncTypeBase, @@ -159,7 +174,7 @@ pub(crate) mod test { let list_def = EXTENSION.get_type(&LIST_TYPENAME).unwrap(); let tyvar = TypeArg::new_var_use(0, TypeBound::Any.into()); let list_of_var = Type::new_extension(list_def.instantiate([tyvar.clone()])?); - let list_len = PolyFuncType::new_validated( + let list_len = TypeSchemeBase::new_validated( [TypeBound::Any.into()], FunctionType::new(vec![list_of_var], vec![USIZE_T]), ®ISTRY, @@ -190,7 +205,7 @@ pub(crate) mod test { // Valid schema... let good_array = Type::new_extension(ar_def.instantiate([tyvar.clone(), szvar.clone()])?); - let good_ts = PolyFuncType::new_validated( + let good_ts = TypeSchemeBase::new_validated( typarams.clone(), FunctionType::new_endo(good_array), &PRELUDE_REGISTRY, @@ -232,7 +247,7 @@ pub(crate) mod test { PRELUDE_ID, TypeBound::Any, )); - let bad_ts = PolyFuncType::new_validated( + let bad_ts = TypeSchemeBase::new_validated( typarams.clone(), FunctionType::new_endo(bad_array), &PRELUDE_REGISTRY, @@ -259,7 +274,7 @@ pub(crate) mod test { }, ] { let invalid_ts = - PolyFuncType::new_validated([decl.clone()], body_type.clone(), ®ISTRY); + TypeSchemeBase::new_validated([decl.clone()], body_type.clone(), ®ISTRY); assert_eq!( invalid_ts.err(), Some(SignatureError::TypeVarDoesNotMatchDeclaration { @@ -269,7 +284,7 @@ pub(crate) mod test { ); } // Variable not declared at all - let invalid_ts = PolyFuncType::new_validated([], body_type, ®ISTRY); + let invalid_ts = TypeSchemeBase::new_validated([], body_type, ®ISTRY); assert_eq!( invalid_ts.err(), Some(SignatureError::FreeTypeVar { @@ -301,7 +316,7 @@ pub(crate) mod test { let reg = ExtensionRegistry::try_new([e]).unwrap(); let make_scheme = |tp: TypeParam| { - PolyFuncType::new_validated( + TypeSchemeBase::new_validated( [tp.clone()], FunctionType::new_endo(Type::new_extension(CustomType::new( TYPE_NAME, @@ -366,7 +381,7 @@ pub(crate) mod test { let decl = TypeParam::List { param: Box::new(TP_ANY), }; - let e = PolyFuncType::new_validated( + let e = TypeSchemeBase::new_validated( [decl.clone()], FunctionTypeRV::new( vec![USIZE_T], @@ -380,7 +395,7 @@ pub(crate) mod test { assert_eq!(cached, TypeParam::List {param: Box::new(TypeParam::Type {b: TypeBound::Copyable})}); }); // Declared as row variable, used as type variable - let e = PolyFuncType::new_validated( + let e = TypeSchemeBase::new_validated( [decl.clone()], FunctionType::new_endo(vec![Type::new_var_use(0, TypeBound::Any)]), &EMPTY_REG, @@ -395,7 +410,7 @@ pub(crate) mod test { #[test] fn row_variables() { let rty = TypeRV::new_row_var_use(0, TypeBound::Any); - let pf = PolyFuncType::new_validated( + let pf = TypeSchemeBase::new_validated( [TypeParam::new_list(TP_ANY)], FunctionTypeRV::new( vec![USIZE_T.into(), rty.clone()], @@ -436,7 +451,7 @@ pub(crate) mod test { 0, TypeBound::Copyable, ))); - let pf = PolyFuncType::new_validated( + let pf = TypeSchemeBase::new_validated( [TypeParam::List { param: Box::new(TypeParam::Type { b: TypeBound::Copyable, diff --git a/hugr-core/src/types/type_param.rs b/hugr-core/src/types/type_param.rs index 7b58e234c..6fd89b942 100644 --- a/hugr-core/src/types/type_param.rs +++ b/hugr-core/src/types/type_param.rs @@ -46,10 +46,10 @@ impl UpperBound { } } -/// A *kind* of [TypeArg]. Thus, a parameter declared by a [PolyFuncType] (e.g. [OpDef]), +/// A *kind* of [TypeArg]. Thus, a parameter declared by a [TypeSchemeRV] (e.g. [OpDef]), /// specifying a value that may (resp. must) be provided to instantiate it. /// -/// [PolyFuncType]: super::PolyFuncType +/// [TypeSchemeRV]: super::TypeSchemeRV /// [OpDef]: crate::extension::OpDef #[derive( Clone, Debug, PartialEq, Eq, derive_more::Display, serde::Deserialize, serde::Serialize, diff --git a/hugr-core/src/utils.rs b/hugr-core/src/utils.rs index 368658faf..a67779d80 100644 --- a/hugr-core/src/utils.rs +++ b/hugr-core/src/utils.rs @@ -112,17 +112,17 @@ pub(crate) mod test_quantum_extension { ops::CustomOp, std_extensions::arithmetic::float_types, type_row, - types::{FunctionType, PolyFuncType}, + types::{FunctionType, TypeSchemeRV}, Extension, }; use lazy_static::lazy_static; - fn one_qb_func() -> PolyFuncType { + fn one_qb_func() -> TypeSchemeRV { FunctionTypeRV::new_endo(QB_T).into() } - fn two_qb_func() -> PolyFuncType { + fn two_qb_func() -> TypeSchemeRV { FunctionTypeRV::new_endo(type_row![QB_T, QB_T]).into() } /// The extension identifier. diff --git a/hugr/src/lib.rs b/hugr/src/lib.rs index aa7de4990..8e6f89ad5 100644 --- a/hugr/src/lib.rs +++ b/hugr/src/lib.rs @@ -43,17 +43,17 @@ //! }, //! ops::{CustomOp, OpName}, //! type_row, -//! types::{FunctionTypeRV, PolyFuncType}, +//! types::{FunctionTypeRV, TypeSchemeRV}, //! Extension, //! }; //! //! use lazy_static::lazy_static; //! -//! fn one_qb_func() -> PolyFuncType { +//! fn one_qb_func() -> TypeSchemeRV { //! FunctionTypeRV::new_endo(type_row![QB_T]).into() //! } //! -//! fn two_qb_func() -> PolyFuncType { +//! fn two_qb_func() -> TypeSchemeRV { //! FunctionTypeRV::new_endo(type_row![QB_T, QB_T]).into() //! } //! /// The extension identifier. From c558ed809a13ac2a6caee2706535cccdedc19c20 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Wed, 26 Jun 2024 14:03:10 +0100 Subject: [PATCH 088/115] (type(row)+serialize).rs only: Type(Row)Base not const bool --- hugr-core/src/types.rs | 190 ++++++++++++++++++++++--------- hugr-core/src/types/serialize.rs | 17 ++- hugr-core/src/types/type_row.rs | 28 ++--- 3 files changed, 161 insertions(+), 74 deletions(-) diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index 53864ae7e..21b654c63 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -8,8 +8,6 @@ mod signature; pub mod type_param; pub mod type_row; -use std::marker::PhantomData; - pub use crate::ops::constant::{ConstTypeError, CustomCheckFailure}; use crate::types::type_param::check_type_arg; use crate::utils::display_list_with_separator; @@ -189,7 +187,7 @@ impl SumType { } } -impl From for TypeBase { +impl From for TypeBase { fn from(sum: SumType) -> Self { match sum { SumType::Unit { size } => TypeBase::new_unit_sum(size), @@ -198,10 +196,85 @@ impl From for TypeBase { } } -#[derive(Clone, PartialEq, Debug, Eq, derive_more::Display)] +/// Variable index, and cache of inner TypeBound - matches a [TypeParam::List] of [TypeParam::Type] +/// of this bound (checked in validation) +// Note that I believe the serde derives here are not used except as markers +// so that other types containing this can also #derive-serde the same way. +#[derive( + Clone, Debug, Eq, PartialEq, derive_more::Display, serde::Serialize, serde::Deserialize, +)] +#[display(fmt = "{}", "_0")] +pub struct RowVariable(usize, TypeBound); + +trait MaybeRV: Clone + std::fmt::Debug + std::fmt::Display + From + Eq + PartialEq + 'static { + fn as_rv(&self) -> &RowVariable; + fn try_from_rv(rv: RowVariable) -> Result; + fn bound(&self) -> TypeBound; + fn validate(&self, var_decls: &[TypeParam]) -> Result<(), SignatureError>; + fn substitute(&self, s: &Substitution) -> Vec>; +} + +// Note that I believe the serde derives here are not used except as markers +// so that other types containing this can also #derive-serde the same way. +#[derive( + Clone, Debug, Eq, PartialEq, derive_more::Display, serde::Serialize, serde::Deserialize, +)] +pub enum NoRV {} + +impl From for RowVariable { + fn from(value: NoRV) -> Self { + match value { } + } +} + +impl MaybeRV for RowVariable { + fn as_rv(&self) -> &RowVariable { + self + } + + fn bound(&self) -> TypeBound { + self.1 + } + + fn validate(&self, var_decls: &[TypeParam]) -> Result<(), SignatureError> { + check_typevar_decl(var_decls, self.0, &TypeParam::new_list(self.1)) + } + + fn substitute(&self, s: &Substitution) -> Vec> { + s.apply_rowvar(self.0, self.1) + } + + fn try_from_rv(rv: RowVariable) -> Result { + Ok(rv) + } +} + +impl MaybeRV for NoRV { + fn as_rv(&self) -> &RowVariable { + match *self {} + } + + fn bound(&self) -> TypeBound { + match *self {} + } + + fn validate(&self, _var_decls: &[TypeParam]) -> Result<(), SignatureError> { + match *self {} + } + + fn substitute(&self, _s: &Substitution) -> Vec> { + match *self {} + } + + fn try_from_rv(rv: RowVariable) -> Result { + Err(SignatureError::RowVarWhereTypeExpected { idx: rv.0 }) + } +} + +#[derive(Clone, Debug, Eq, derive_more::Display)] #[cfg_attr(test, derive(Arbitrary), proptest(params = "RecursionDepth"))] /// Core types -pub enum TypeEnum { +pub enum TypeEnum { // TODO optimise with Box ? // or some static version of this? #[allow(missing_docs)] @@ -224,23 +297,23 @@ pub enum TypeEnum { #[allow(missing_docs)] #[display(fmt = "Variable({})", _0)] Variable(usize, TypeBound), - /// Variable index, and cache of inner TypeBound - matches a [TypeParam::List] of [TypeParam::Type] - /// of this bound (checked in validation). Should only exist for `Type`. + /// RowVariable. Of course, this requires that `RV` has instances, [NoRV] doesn't. #[display(fmt = "RowVar({})", _0)] - RowVariable(usize, TypeBound), + RowVar(RV), #[allow(missing_docs)] #[display(fmt = "{}", "_0")] Sum(#[cfg_attr(test, proptest(strategy = "any_with::(params)"))] SumType), } -impl TypeEnum { +impl TypeEnum { /// The smallest type bound that covers the whole type. fn least_upper_bound(&self) -> TypeBound { match self { TypeEnum::Extension(c) => c.bound(), TypeEnum::Alias(a) => a.bound, TypeEnum::Function(_) => TypeBound::Copyable, - TypeEnum::Variable(_, b) | TypeEnum::RowVariable(_, b) => *b, + TypeEnum::Variable(_, b) => *b, + TypeEnum::RowVar(b) => b.bound(), TypeEnum::Sum(SumType::Unit { size: _ }) => TypeBound::Eq, TypeEnum::Sum(SumType::General { rows }) => least_upper_bound( rows.iter() @@ -251,11 +324,6 @@ impl TypeEnum { } } -struct Implies(PhantomData>, PhantomData>); -impl Implies { - const A_IMPLIES_B: () = assert!(B || !A); -} - #[derive(Clone, Debug, Eq, derive_more::Display, serde::Serialize, serde::Deserialize)] #[display(fmt = "{}", "_0")] #[serde( @@ -282,22 +350,36 @@ impl Implies { /// let func_type: Type = Type::new_function(FunctionType::new_endo(vec![])); /// assert_eq!(func_type.least_upper_bound(), TypeBound::Copyable); /// ``` -pub struct TypeBase(TypeEnum, TypeBound); +pub struct TypeBase(TypeEnum, TypeBound); /// The type of a single value, that can be sent down a wire -pub type Type = TypeBase; +pub type Type = TypeBase; /// One or more types - either a single type, or a row variable /// standing for multiple types. -pub type TypeRV = TypeBase; +pub type TypeRV = TypeBase; + +impl PartialEq> for TypeEnum { + fn eq(&self, other: &TypeEnum) -> bool { + match (self, other) { + (TypeEnum::Extension(e1), TypeEnum::Extension(e2)) => e1 == e2, + (TypeEnum::Alias(a1), TypeEnum::Alias(a2)) => a1 == a2, + (TypeEnum::Function(f1), TypeEnum::Function(f2)) => f1 == f2, + (TypeEnum::Variable(i1, b1), TypeEnum::Variable(i2, b2)) => i1 == i2 && b1 == b2, + (TypeEnum::RowVar(v1), TypeEnum::RowVar(v2)) => v1.as_rv() == v2.as_rv(), + (TypeEnum::Sum(s1), TypeEnum::Sum(s2)) => s1 == s2, + _ => false, + } + } +} -impl PartialEq> for TypeBase { +impl PartialEq> for TypeBase { fn eq(&self, other: &TypeBase) -> bool { self.0 == other.0 && self.1 == other.1 } } -impl TypeBase { +impl TypeBase { /// An empty `TypeRow` or `TypeRowRV`. Provided here for convenience pub const EMPTY_TYPEROW: TypeRowBase = TypeRowBase::::new(); /// Unit type (empty tuple). @@ -341,9 +423,7 @@ impl TypeBase { Self::new(TypeEnum::Alias(alias)) } - fn new(type_e: TypeEnum) -> Self { - // private method - so we can be sure of this: - debug_assert!(RV || !matches!(type_e, TypeEnum::RowVariable(_, _))); + fn new(type_e: TypeEnum) -> Self { let bound = type_e.least_upper_bound(); Self(type_e, bound) } @@ -370,7 +450,7 @@ impl TypeBase { /// Report the component TypeEnum. #[inline(always)] - pub const fn as_type_enum(&self) -> &TypeEnum { + pub const fn as_type_enum(&self) -> &TypeEnum { &self.0 } @@ -407,13 +487,7 @@ impl TypeBase { // (i.e. with row vars) as long as they are not called: TypeEnum::Function(ft) => ft.validate(extension_registry, var_decls), TypeEnum::Variable(idx, bound) => check_typevar_decl(var_decls, *idx, &(*bound).into()), - TypeEnum::RowVariable(idx, bound) => { - if RV { - check_typevar_decl(var_decls, *idx, &TypeParam::new_list(*bound)) - } else { - Err(SignatureError::RowVarWhereTypeExpected { idx: *idx }) - } - } + TypeEnum::RowVar(rv) => rv.validate(var_decls), } } @@ -425,12 +499,7 @@ impl TypeBase { /// return a Vec containing any number of [Type]s. These may (or not) pass [Type::validate] fn substitute(&self, t: &Substitution) -> Vec { match &self.0 { - TypeEnum::RowVariable(idx, bound) => { - let res = t.apply_rowvar(*idx, *bound); // these are Type's - assert!(RV); - // We need Types, so use try_into_(). Since we know RV==true, this cannot fail. - res.into_iter().map(|t| t.try_into_().unwrap()).collect() - } + TypeEnum::RowVar(rv) => rv.substitute(t), TypeEnum::Alias(_) | TypeEnum::Sum(SumType::Unit { .. }) => vec![self.clone()], TypeEnum::Variable(idx, bound) => { let TypeArg::Type { ty } = t.apply_var(*idx, &((*bound).into())) else { @@ -458,7 +527,7 @@ impl Type { impl TypeRV { /// Tells if this Type is a row variable, i.e. could stand for any number >=0 of Types pub fn is_row_var(&self) -> bool { - matches!(self.0, TypeEnum::RowVariable(_, _)) + matches!(self.0, TypeEnum::RowVar(_)) } /// New use (occurrence) of the row variable with specified index. @@ -469,30 +538,41 @@ impl TypeRV { /// [OpDef]: crate::extension::OpDef /// [FuncDefn]: crate::ops::FuncDefn pub const fn new_row_var_use(idx: usize, bound: TypeBound) -> Self { - Self(TypeEnum::RowVariable(idx, bound), bound) + Self(TypeEnum::RowVar(RowVariable(idx, bound)), bound) } } // ====== Conversions ====== impl TypeRV { - fn try_into_(self) -> Result, SignatureError> { - if !RV { - if let TypeEnum::RowVariable(idx, _) = self.0 { - return Err(SignatureError::RowVarWhereTypeExpected { idx }); - } - } - Ok(TypeBase(self.0, self.1)) + fn try_into_(self) -> Result, SignatureError> { + Ok(TypeBase( + match self.0 { + TypeEnum::Extension(e) => TypeEnum::Extension(e), + TypeEnum::Alias(a) => TypeEnum::Alias(a), + TypeEnum::Function(f) => TypeEnum::Function(f), + TypeEnum::Variable(idx, bound) => TypeEnum::Variable(idx, bound), + TypeEnum::RowVar(rv) => TypeEnum::RowVar(RV::try_from_rv(rv)?), + TypeEnum::Sum(s) => TypeEnum::Sum(s), + }, + self.1, + )) } } -impl TypeBase { - /// A swiss-army-knife for any safe conversion of the const-bool "type" argument - /// to/from true/false/variable. Any unsafe conversion (that might create - /// a [Type] of a [TypeEnum::RowVariable]) will fail statically with an assert. - fn into_(self) -> TypeBase { - #[allow(clippy::let_unit_value)] - let _ = Implies::::A_IMPLIES_B; - TypeBase(self.0, self.1) +impl TypeBase { + /// A swiss-army-knife for any safe conversion of the type argument `RV1` + /// to/from [NoRV]/RowVariable/rust-type-variable. + fn into_(self) -> TypeBase where RV1: Into { + TypeBase( + match self.0 { + TypeEnum::Extension(e) => TypeEnum::Extension(e), + TypeEnum::Alias(a) => TypeEnum::Alias(a), + TypeEnum::Function(f) => TypeEnum::Function(f), + TypeEnum::Variable(idx, bound) => TypeEnum::Variable(idx, bound), + TypeEnum::RowVar(rv) => TypeEnum::RowVar(rv.into()), + TypeEnum::Sum(s) => TypeEnum::Sum(s), + }, self.1 + ) } } @@ -545,7 +625,7 @@ impl<'a> Substitution<'a> { panic!("Not a list of types - call validate() ?") }) .collect(), - TypeArg::Type { ty } if matches!(ty.0, TypeEnum::RowVariable(_, _)) => { + TypeArg::Type { ty } if matches!(ty.0, TypeEnum::RowVar(_)) => { // Standalone "Type" can be used iff its actually a Row Variable not an actual (single) Type vec![ty.clone().into()] } diff --git a/hugr-core/src/types/serialize.rs b/hugr-core/src/types/serialize.rs index 4bae0eead..dc46e1b29 100644 --- a/hugr-core/src/types/serialize.rs +++ b/hugr-core/src/types/serialize.rs @@ -1,4 +1,6 @@ -use super::{FunctionTypeRV, SumType, TypeArg, TypeBase, TypeBound, TypeEnum}; +use super::{ + FunctionTypeRV, MaybeRV, RowVariable, SumType, TypeArg, TypeBase, TypeBound, TypeEnum, +}; use super::custom::CustomType; @@ -20,7 +22,7 @@ pub(super) enum SerSimpleType { R { i: usize, b: TypeBound }, } -impl From> for SerSimpleType { +impl From> for SerSimpleType { fn from(value: TypeBase) -> Self { if value == QB_T { return SerSimpleType::Q; @@ -33,13 +35,16 @@ impl From> for SerSimpleType { TypeEnum::Alias(a) => SerSimpleType::Alias(a), TypeEnum::Function(sig) => SerSimpleType::G(sig), TypeEnum::Variable(i, b) => SerSimpleType::V { i, b }, - TypeEnum::RowVariable(i, b) => SerSimpleType::R { i, b }, + TypeEnum::RowVar(rv) => { + let RowVariable(idx, bound) = rv.as_rv(); + SerSimpleType::R { i: *idx, b: *bound } + } TypeEnum::Sum(st) => SerSimpleType::Sum(st), } } } -impl TryFrom for TypeBase { +impl TryFrom for TypeBase { type Error = SignatureError; fn try_from(value: SerSimpleType) -> Result { Ok(match value { @@ -54,7 +59,9 @@ impl TryFrom for TypeBase { SerSimpleType::Alias(a) => TypeBase::new_alias(a), SerSimpleType::V { i, b } => TypeBase::new_var_use(i, b), // We can't use new_row_var because that returns Type not Type. - SerSimpleType::R { i, b } => TypeBase::new(TypeEnum::RowVariable(i, b)).try_into_()?, + SerSimpleType::R { i, b } => { + TypeBase::new(TypeEnum::RowVar(RV::try_from_rv(RowVariable(i, b))?)) + } }) } } diff --git a/hugr-core/src/types/type_row.rs b/hugr-core/src/types/type_row.rs index 63008c3b4..94440513f 100644 --- a/hugr-core/src/types/type_row.rs +++ b/hugr-core/src/types/type_row.rs @@ -7,7 +7,7 @@ use std::{ ops::{Deref, DerefMut}, }; -use super::{type_param::TypeParam, Substitution, Type, TypeBase}; +use super::{type_param::TypeParam, MaybeRV, NoRV, RowVariable, Substitution, Type, TypeBase}; use crate::{ extension::{ExtensionRegistry, SignatureError}, utils::display_list, @@ -22,18 +22,18 @@ use itertools::Itertools; #[derive(Clone, Eq, Debug, serde::Serialize, serde::Deserialize)] #[non_exhaustive] #[serde(transparent)] -pub struct TypeRowBase { +pub struct TypeRowBase { /// The datatypes in the row. types: Cow<'static, [TypeBase]>, } /// Row of single types i.e. of known length, for node inputs/outputs -pub type TypeRow = TypeRowBase; +pub type TypeRow = TypeRowBase; /// Row of types and/or row variables, the number of actual types is thus unknown -pub type TypeRowRV = TypeRowBase; +pub type TypeRowRV = TypeRowBase; -impl PartialEq> for TypeRowBase { +impl PartialEq> for TypeRowBase { fn eq(&self, other: &TypeRowBase) -> bool { self.types.len() == other.types.len() && self @@ -44,7 +44,7 @@ impl PartialEq> for TypeRowBa } } -impl Display for TypeRowBase { +impl Display for TypeRowBase { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_char('[')?; display_list(self.types.as_ref(), f)?; @@ -52,7 +52,7 @@ impl Display for TypeRowBase { } } -impl TypeRowBase { +impl TypeRowBase { /// Create a new empty row. pub const fn new() -> Self { Self { @@ -138,13 +138,13 @@ impl TryFrom for TypeRow { } } -impl Default for TypeRowBase { +impl Default for TypeRowBase { fn default() -> Self { Self::new() } } -impl From>> for TypeRowBase { +impl From>> for TypeRowBase { fn from(types: Vec>) -> Self { Self { types: types.into(), @@ -168,7 +168,7 @@ impl From for TypeRowRV { } } -impl From<&'static [TypeBase]> for TypeRowBase { +impl From<&'static [TypeBase]> for TypeRowBase { fn from(types: &'static [TypeBase]) -> Self { Self { types: types.into(), @@ -176,7 +176,7 @@ impl From<&'static [TypeBase]> for TypeRowBase { } } -impl From> for TypeRowRV { +impl> From> for TypeRowRV { fn from(t: TypeBase) -> Self { Self { types: vec![t.into_()].into(), @@ -192,7 +192,7 @@ impl From for TypeRow { } } -impl Deref for TypeRowBase { +impl Deref for TypeRowBase { type Target = [TypeBase]; fn deref(&self) -> &Self::Target { @@ -200,7 +200,7 @@ impl Deref for TypeRowBase { } } -impl DerefMut for TypeRowBase { +impl DerefMut for TypeRowBase { fn deref_mut(&mut self) -> &mut Self::Target { self.types.to_mut() } @@ -213,7 +213,7 @@ mod test { use crate::types::{TypeBase, TypeRowBase}; use ::proptest::prelude::*; - impl Arbitrary for super::super::TypeRowBase { + impl Arbitrary for super::super::TypeRowBase { type Parameters = RecursionDepth; type Strategy = BoxedStrategy; fn arbitrary_with(depth: Self::Parameters) -> Self::Strategy { From 536b233248b70eb894fde0bb44f8b84407e8b359 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Wed, 26 Jun 2024 14:42:39 +0100 Subject: [PATCH 089/115] try_into_+try_from_rv err w/ RowVariable not SigError; SigError contains RowVariable --- hugr-core/src/extension.rs | 5 +++-- hugr-core/src/types.rs | 16 ++++++++-------- hugr-core/src/types/check.rs | 4 ++-- hugr-core/src/types/serialize.rs | 3 ++- 4 files changed, 15 insertions(+), 13 deletions(-) diff --git a/hugr-core/src/extension.rs b/hugr-core/src/extension.rs index 0dfd9a13b..964797649 100644 --- a/hugr-core/src/extension.rs +++ b/hugr-core/src/extension.rs @@ -16,6 +16,7 @@ use crate::ops::constant::{ValueName, ValueNameRef}; use crate::ops::custom::{ExtensionOp, OpaqueOp}; use crate::ops::{self, OpName, OpNameRef}; use crate::types::type_param::{TypeArg, TypeArgError, TypeParam}; +use crate::types::RowVariable; use crate::types::{check_typevar_decl, CustomType, Substitution, TypeBound, TypeName}; use crate::types::{FunctionType, TypeNameRef}; @@ -155,8 +156,8 @@ pub enum SignatureError { #[error("Type variable {idx} was not declared ({num_decls} in scope)")] FreeTypeVar { idx: usize, num_decls: usize }, /// A row variable was found outside of a variable-length row - #[error("Expected a single type, but found row variable {idx}")] - RowVarWhereTypeExpected { idx: usize }, + #[error("Expected a single type, but found row variable {var}")] + RowVarWhereTypeExpected { var: RowVariable }, /// The result of the type application stored in a [Call] /// is not what we get by applying the type-args to the polymorphic function /// diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index 21b654c63..6d969003c 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -208,7 +208,7 @@ pub struct RowVariable(usize, TypeBound); trait MaybeRV: Clone + std::fmt::Debug + std::fmt::Display + From + Eq + PartialEq + 'static { fn as_rv(&self) -> &RowVariable; - fn try_from_rv(rv: RowVariable) -> Result; + fn try_from_rv(rv: RowVariable) -> Result; fn bound(&self) -> TypeBound; fn validate(&self, var_decls: &[TypeParam]) -> Result<(), SignatureError>; fn substitute(&self, s: &Substitution) -> Vec>; @@ -244,7 +244,7 @@ impl MaybeRV for RowVariable { s.apply_rowvar(self.0, self.1) } - fn try_from_rv(rv: RowVariable) -> Result { + fn try_from_rv(rv: RowVariable) -> Result { Ok(rv) } } @@ -266,8 +266,8 @@ impl MaybeRV for NoRV { match *self {} } - fn try_from_rv(rv: RowVariable) -> Result { - Err(SignatureError::RowVarWhereTypeExpected { idx: rv.0 }) + fn try_from_rv(rv: RowVariable) -> Result { + Err(rv) } } @@ -543,15 +543,15 @@ impl TypeRV { } // ====== Conversions ====== -impl TypeRV { - fn try_into_(self) -> Result, SignatureError> { +impl TypeBase { + fn try_into_(self) -> Result { Ok(TypeBase( match self.0 { TypeEnum::Extension(e) => TypeEnum::Extension(e), TypeEnum::Alias(a) => TypeEnum::Alias(a), TypeEnum::Function(f) => TypeEnum::Function(f), TypeEnum::Variable(idx, bound) => TypeEnum::Variable(idx, bound), - TypeEnum::RowVar(rv) => TypeEnum::RowVar(RV::try_from_rv(rv)?), + TypeEnum::RowVar(rv) => {return Err(rv.as_rv().clone())}, TypeEnum::Sum(s) => TypeEnum::Sum(s), }, self.1, @@ -585,7 +585,7 @@ impl From for TypeRV { impl TryFrom for Type { type Error = SignatureError; fn try_from(value: TypeRV) -> Result { - value.try_into_() + value.try_into_().map_err(|var| SignatureError::RowVarWhereTypeExpected { var }) } } diff --git a/hugr-core/src/types/check.rs b/hugr-core/src/types/check.rs index 95343c0fc..2146ee41b 100644 --- a/hugr-core/src/types/check.rs +++ b/hugr-core/src/types/check.rs @@ -69,10 +69,10 @@ impl super::SumType { num_variants: self.num_variants(), })?; let variant: TypeRow = variant.clone().try_into().map_err(|e| { - let SignatureError::RowVarWhereTypeExpected { idx } = e else { + let SignatureError::RowVarWhereTypeExpected { var } = e else { panic!("Unexpected error") }; - SumTypeError::VariantNotConcrete { tag, varidx: idx } + SumTypeError::VariantNotConcrete { tag, varidx: var.0 } })?; if variant.len() != val.len() { diff --git a/hugr-core/src/types/serialize.rs b/hugr-core/src/types/serialize.rs index dc46e1b29..622344ea4 100644 --- a/hugr-core/src/types/serialize.rs +++ b/hugr-core/src/types/serialize.rs @@ -60,7 +60,8 @@ impl TryFrom for TypeBase { SerSimpleType::V { i, b } => TypeBase::new_var_use(i, b), // We can't use new_row_var because that returns Type not Type. SerSimpleType::R { i, b } => { - TypeBase::new(TypeEnum::RowVar(RV::try_from_rv(RowVariable(i, b))?)) + TypeBase::new(TypeEnum::RowVar(RV::try_from_rv(RowVariable(i, b)) + .map_err(|var| SignatureError::RowVarWhereTypeExpected { var })?)) } }) } From a59b1ea4ac64214d350acdbef09d4bafdfd346c7 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Wed, 26 Jun 2024 14:43:20 +0100 Subject: [PATCH 090/115] Fix type_param.rs --- hugr-core/src/types/type_param.rs | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/hugr-core/src/types/type_param.rs b/hugr-core/src/types/type_param.rs index 6fd89b942..9e9cc9a73 100644 --- a/hugr-core/src/types/type_param.rs +++ b/hugr-core/src/types/type_param.rs @@ -14,7 +14,7 @@ use crate::extension::ExtensionRegistry; use crate::extension::ExtensionSet; use crate::extension::SignatureError; -use super::{check_typevar_decl, CustomType, Substitution, Type, TypeBase, TypeBound, TypeEnum}; +use super::{check_typevar_decl, CustomType, MaybeRV, RowVariable, Substitution, Type, TypeBase, TypeBound}; /// The upper non-inclusive bound of a [`TypeParam::BoundedNat`] // A None inner value implies the maximum bound: u64::MAX + 1 (all u64 values valid) @@ -183,15 +183,12 @@ pub enum TypeArg { }, } -impl From> for TypeArg { +impl From> for TypeArg { fn from(ty: TypeBase) -> Self { - if let TypeEnum::RowVariable(idx, bound) = ty.0 { - assert!(RV); + match ty.try_into_() { + Ok(ty) => TypeArg::Type {ty}, + Err(RowVariable(idx, bound)) => TypeArg::new_var_use(idx, TypeParam::new_list(bound)) - } else { - TypeArg::Type { - ty: TypeBase(ty.0, ty.1), - } } } } From c2344424da5b4402e8b016bc69ee0363840ca9d5 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Wed, 26 Jun 2024 14:46:48 +0100 Subject: [PATCH 091/115] signature.rs --- hugr-core/src/types/signature.rs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index c1f32360c..a519e6254 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -6,7 +6,7 @@ use std::fmt::{self, Display, Write}; use super::type_param::TypeParam; use super::type_row::TypeRowBase; -use super::{Substitution, Type, TypeBound, TypeEnum, TypeRow}; +use super::{MaybeRV, NoRV, RowVariable, Substitution, Type, TypeEnum, TypeRow}; use crate::core::PortIndex; use crate::extension::{ExtensionRegistry, ExtensionSet, SignatureError}; @@ -24,7 +24,7 @@ use {crate::proptest::RecursionDepth, ::proptest::prelude::*, proptest_derive::A /// /// [Graph]: crate::ops::constant::Value::Function /// [RowVariable]: crate::types::TypeEnum::RowVariable -pub struct FuncTypeBase { +pub struct FuncTypeBase { /// Value inputs of the function. #[cfg_attr(test, proptest(strategy = "any_with::>(params)"))] pub input: TypeRowBase, @@ -37,15 +37,15 @@ pub struct FuncTypeBase { /// The concept of "signature" in the spec - the edges required to/from a node or graph /// and also the target (value) of a call (static). -pub type FunctionType = FuncTypeBase; +pub type FunctionType = FuncTypeBase; /// A function that may contain [RowVariable]s and thus has potentially-unknown arity; /// passable as a value round a Hugr (see [Type::new_function]) but not a valid node type. /// /// [RowVariable]: crate::types::TypeEnum::RowVariable -pub type FunctionTypeRV = FuncTypeBase; +pub type FunctionTypeRV = FuncTypeBase; -impl FuncTypeBase { +impl FuncTypeBase { /// Builder method, add extension_reqs to an FunctionType pub fn with_extension_delta(mut self, rs: impl Into) -> Self { self.extension_reqs = self.extension_reqs.union(rs.into()); @@ -108,12 +108,12 @@ impl FuncTypeBase { impl FunctionTypeRV { /// If this FunctionType contains any row variables, return one. - pub fn find_rowvar(&self) -> Option<(usize, TypeBound)> { + pub fn find_rowvar(&self) -> Option { self.input .iter() .chain(self.output.iter()) - .find_map(|t| match t.0 { - TypeEnum::RowVariable(idx, bound) => Some((idx, bound)), + .find_map(|t| match &t.0 { + TypeEnum::RowVar(rv) => Some(rv.clone()), _ => None, }) } @@ -233,7 +233,7 @@ impl FunctionType { } } -impl Display for FuncTypeBase { +impl Display for FuncTypeBase { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if !self.input.is_empty() { self.input.fmt(f)?; @@ -266,7 +266,7 @@ impl From for FunctionTypeRV { } } -impl PartialEq> for FuncTypeBase { +impl PartialEq> for FuncTypeBase { fn eq(&self, other: &FuncTypeBase) -> bool { self.input == other.input && self.output == other.output From dd099ac0fe1e2413910a4b12119f3a485703ef6b Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Wed, 26 Jun 2024 18:22:28 +0100 Subject: [PATCH 092/115] poly_func.rs --- hugr-core/src/types/poly_func.rs | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index f0a834175..12896b21f 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -9,7 +9,7 @@ use { proptest_derive::Arbitrary, }; -use super::signature::FuncTypeBase; +use super::{signature::FuncTypeBase, MaybeRV, NoRV, RowVariable}; use super::type_param::{check_type_args, TypeArg, TypeParam}; use super::Substitution; @@ -28,7 +28,7 @@ use super::Substitution; "params.iter().map(ToString::to_string).join(\" \")", "body" )] -pub struct TypeSchemeBase { +pub struct TypeSchemeBase { /// The declared type parameters, i.e., these must be instantiated with /// the same number of [TypeArg]s before the function can be called. This /// defines the indices used by variables inside the body. @@ -45,16 +45,15 @@ pub struct TypeSchemeBase { /// [Call]: crate::ops::Call /// [FuncDefn]: crate::ops::FuncDefn /// [FuncDecl]: crate::ops::FuncDecl -pub type TypeScheme = TypeSchemeBase; +pub type TypeScheme = TypeSchemeBase; /// The polymorphic type of an [OpDef], whose number of input and outputs /// may vary according to how [RowVariable]s therein are instantiated. /// /// ]OpDef]: crate::extension::OpDef -/// [RowVariable]: crate::types::TypeEnum::RowVariable -pub type TypeSchemeRV = TypeSchemeBase; +pub type TypeSchemeRV = TypeSchemeBase; -impl From> for TypeSchemeBase { +impl From> for TypeSchemeBase { fn from(body: FuncTypeBase) -> Self { Self { params: vec![], @@ -72,8 +71,8 @@ impl From for TypeSchemeRV { } } -impl TryFrom> for FuncTypeBase { - /// If the TypeSchemeBase is not monomorphic, fail with its binders +impl TryFrom> for FuncTypeBase { + /// If the PolyFuncType is not monomorphic, fail with its binders type Error = Vec; fn try_from(value: TypeSchemeBase) -> Result { @@ -85,7 +84,7 @@ impl TryFrom> for FuncTypeBase { } } -impl TypeSchemeBase { +impl TypeSchemeBase { /// The type parameters, aka binders, over which this type is polymorphic pub fn params(&self) -> &[TypeParam] { &self.params @@ -157,7 +156,7 @@ pub(crate) mod test { ExtensionRegistry::try_new([PRELUDE.to_owned(), EXTENSION.to_owned()]).unwrap(); } - impl TypeSchemeBase { + impl TypeSchemeBase { fn new_validated( params: impl Into>, body: FuncTypeBase, From 9eef77b92a2d63863382327792358512f50fe11c Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Wed, 26 Jun 2024 22:46:01 +0100 Subject: [PATCH 093/115] impl Default explicitly, regardless of RV --- hugr-core/src/types/poly_func.rs | 9 ++++++++- hugr-core/src/types/signature.rs | 9 ++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index 12896b21f..c0a0a7302 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -20,7 +20,7 @@ use super::Substitution; /// [FuncDefn]: crate::ops::module::FuncDefn /// [OpDef]: crate::extension::OpDef #[derive( - Clone, PartialEq, Debug, Default, Eq, derive_more::Display, serde::Serialize, serde::Deserialize, + Clone, PartialEq, Debug, Eq, derive_more::Display, serde::Serialize, serde::Deserialize, )] #[cfg_attr(test, derive(Arbitrary), proptest(params = "RecursionDepth"))] #[display( @@ -53,6 +53,13 @@ pub type TypeScheme = TypeSchemeBase; /// ]OpDef]: crate::extension::OpDef pub type TypeSchemeRV = TypeSchemeBase; +// deriving Default leads to an impl that only applies for RV: Default +impl Default for TypeSchemeBase { + fn default() -> Self { + Self { params: Default::default(), body: Default::default() } + } +} + impl From> for TypeSchemeBase { fn from(body: FuncTypeBase) -> Self { Self { diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index a519e6254..b903c5e52 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -15,7 +15,7 @@ use crate::{Direction, IncomingPort, OutgoingPort, Port}; #[cfg(test)] use {crate::proptest::RecursionDepth, ::proptest::prelude::*, proptest_derive::Arbitrary}; -#[derive(Clone, Debug, Default, Eq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug, Eq, serde::Serialize, serde::Deserialize)] #[cfg_attr(test, derive(Arbitrary), proptest(params = "RecursionDepth"))] /// Describes the edges required to/from a node (when ROWVARS=false); /// or (when ROWVARS=true) the type of a [Graph] or the inputs/outputs from an OpDef @@ -119,6 +119,13 @@ impl FunctionTypeRV { } } +// deriving Default leads to an impl that only applies for RV: Default +impl Default for FuncTypeBase { + fn default() -> Self { + Self { input: Default::default(), output: Default::default(), extension_reqs: Default::default() } + } +} + impl FunctionType { /// Returns the type of a value [`Port`]. Returns `None` if the port is out /// of bounds. From 538946e6239de8498dfc3a8623a1c994c530c3f7 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Thu, 27 Jun 2024 11:23:56 +0100 Subject: [PATCH 094/115] proptest - no RowVars at all atm --- hugr-core/src/types.rs | 51 +++++++++++++++++++++----------- hugr-core/src/types/poly_func.rs | 2 +- hugr-core/src/types/type_row.rs | 4 +-- 3 files changed, 36 insertions(+), 21 deletions(-) diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index 6d969003c..e2f724fc0 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -23,7 +23,7 @@ use itertools::FoldWhile::{Continue, Done}; use itertools::{repeat_n, Itertools}; use serde::{Deserialize, Serialize}; #[cfg(test)] -use {crate::proptest::RecursionDepth, ::proptest::prelude::*, proptest_derive::Arbitrary}; +use {proptest_derive::Arbitrary}; use crate::extension::{ExtensionRegistry, SignatureError}; use crate::ops::AliasDecl; @@ -203,6 +203,7 @@ impl From for TypeBase { #[derive( Clone, Debug, Eq, PartialEq, derive_more::Display, serde::Serialize, serde::Deserialize, )] +#[cfg_attr(test, derive(Arbitrary))] #[display(fmt = "{}", "_0")] pub struct RowVariable(usize, TypeBound); @@ -212,6 +213,7 @@ trait MaybeRV: Clone + std::fmt::Debug + std::fmt::Display + From + Eq + P fn bound(&self) -> TypeBound; fn validate(&self, var_decls: &[TypeParam]) -> Result<(), SignatureError>; fn substitute(&self, s: &Substitution) -> Vec>; + #[cfg(test)] fn weight() -> u32 {1} } // Note that I believe the serde derives here are not used except as markers @@ -269,28 +271,27 @@ impl MaybeRV for NoRV { fn try_from_rv(rv: RowVariable) -> Result { Err(rv) } + + #[cfg(test)] + fn weight() -> u32 { + 0 + } } #[derive(Clone, Debug, Eq, derive_more::Display)] -#[cfg_attr(test, derive(Arbitrary), proptest(params = "RecursionDepth"))] +//#[cfg_attr(test, derive(Arbitrary), proptest(params = "RecursionDepth"))] // handles RowVariable, not NoRV /// Core types pub enum TypeEnum { // TODO optimise with Box ? // or some static version of this? #[allow(missing_docs)] - Extension( - #[cfg_attr(test, proptest(strategy = "any_with::(params.into())"))] CustomType, - ), + Extension(CustomType,), #[allow(missing_docs)] #[display(fmt = "Alias({})", "_0.name()")] Alias(AliasDecl), #[allow(missing_docs)] #[display(fmt = "Function({})", "_0")] Function( - #[cfg_attr( - test, - proptest(strategy = "any_with::(params).prop_map(Box::new)") - )] Box, ), // Index into TypeParams, and cache of TypeBound (checked in validation) @@ -302,7 +303,7 @@ pub enum TypeEnum { RowVar(RV), #[allow(missing_docs)] #[display(fmt = "{}", "_0")] - Sum(#[cfg_attr(test, proptest(strategy = "any_with::(params)"))] SumType), + Sum(SumType), } impl TypeEnum { @@ -705,8 +706,9 @@ pub(crate) mod test { use crate::proptest::RecursionDepth; - use crate::types::{SumType, TypeEnum, TypeRow}; + use crate::types::{CustomType, FunctionTypeRV, SumType, TypeRowRV}; use ::proptest::prelude::*; + use super::{AliasDecl, MaybeRV, NoRV, TypeBase, TypeBound}; impl Arbitrary for super::SumType { type Parameters = RecursionDepth; @@ -716,23 +718,36 @@ pub(crate) mod test { if depth.leaf() { any::().prop_map(Self::new_unary).boxed() } else { - vec(any_with::(depth), 0..3) + vec(any_with::(depth), 0..3) .prop_map(SumType::new) .boxed() } } } - impl Arbitrary for super::TypeBase { + impl Arbitrary for NoRV { + type Parameters = (); + + fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy { + panic!("Should be ruled out by weight==0") + } + + type Strategy = BoxedStrategy; + } + + impl Arbitrary for TypeBase { type Parameters = RecursionDepth; type Strategy = BoxedStrategy; fn arbitrary_with(depth: Self::Parameters) -> Self::Strategy { // We descend here, because a TypeEnum may contain a Type - any_with::(depth.descend()) - .prop_filter("Type cannot be a Row Variable", |t| { - RV || !matches!(t, TypeEnum::RowVariable(_, _)) - }) - .prop_map(Self::new) + let depth = depth.descend(); + prop_oneof![ + any::().prop_map(TypeBase::new_alias), + any_with::(depth.into()).prop_map(TypeBase::new_extension), + any_with::(depth).prop_map(TypeBase::new_function), + any_with::(depth).prop_map(TypeBase::from), + (any::(), any::()).prop_map(|(i,b)| TypeBase::new_var_use(i,b)) + ] .boxed() } } diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index c0a0a7302..790bf0766 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -152,7 +152,7 @@ pub(crate) mod test { use crate::types::signature::FuncTypeBase; use crate::types::type_param::{TypeArg, TypeArgError, TypeParam}; use crate::types::{ - CustomType, FunctionType, FunctionTypeRV, Type, TypeBound, TypeName, TypeRV, + CustomType, FunctionType, FunctionTypeRV, MaybeRV, Type, TypeBound, TypeName, TypeRV }; use crate::Extension; diff --git a/hugr-core/src/types/type_row.rs b/hugr-core/src/types/type_row.rs index 94440513f..fa1bb3617 100644 --- a/hugr-core/src/types/type_row.rs +++ b/hugr-core/src/types/type_row.rs @@ -210,10 +210,10 @@ impl DerefMut for TypeRowBase { mod test { mod proptest { use crate::proptest::RecursionDepth; - use crate::types::{TypeBase, TypeRowBase}; + use crate::types::{MaybeRV, TypeBase, TypeRowBase}; use ::proptest::prelude::*; - impl Arbitrary for super::super::TypeRowBase { + impl Arbitrary for super::super::TypeRowBase where TypeBase: Arbitrary { type Parameters = RecursionDepth; type Strategy = BoxedStrategy; fn arbitrary_with(depth: Self::Parameters) -> Self::Strategy { From 4783d29c323f60d25156513e34eb1ded630c7637 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Thu, 27 Jun 2024 11:52:03 +0100 Subject: [PATCH 095/115] Try to add RowVars, but derive constraints breaking --- hugr-core/src/types.rs | 17 ++++++++++------- hugr-core/src/types/type_row.rs | 2 +- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index e2f724fc0..d37714608 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -708,7 +708,7 @@ pub(crate) mod test { use crate::types::{CustomType, FunctionTypeRV, SumType, TypeRowRV}; use ::proptest::prelude::*; - use super::{AliasDecl, MaybeRV, NoRV, TypeBase, TypeBound}; + use super::{AliasDecl, MaybeRV, NoRV, TypeBase, TypeBound, TypeEnum}; impl Arbitrary for super::SumType { type Parameters = RecursionDepth; @@ -735,18 +735,21 @@ pub(crate) mod test { type Strategy = BoxedStrategy; } - impl Arbitrary for TypeBase { + impl Arbitrary for TypeBase { type Parameters = RecursionDepth; type Strategy = BoxedStrategy; fn arbitrary_with(depth: Self::Parameters) -> Self::Strategy { // We descend here, because a TypeEnum may contain a Type let depth = depth.descend(); prop_oneof![ - any::().prop_map(TypeBase::new_alias), - any_with::(depth.into()).prop_map(TypeBase::new_extension), - any_with::(depth).prop_map(TypeBase::new_function), - any_with::(depth).prop_map(TypeBase::from), - (any::(), any::()).prop_map(|(i,b)| TypeBase::new_var_use(i,b)) + 1 => any::().prop_map(TypeBase::new_alias), + 1 => any_with::(depth.into()).prop_map(TypeBase::new_extension), + 1 => any_with::(depth).prop_map(TypeBase::new_function), + 1 => any_with::(depth).prop_map(TypeBase::from), + 1 => (any::(), any::()).prop_map(|(i,b)| TypeBase::new_var_use(i,b)), + // proptest_derive::Arbitrary's weight attribute requires a constant, + // rather than this expression, hence the manual impl: + RV::weight() => any::().prop_map(|rv| TypeBase::new(TypeEnum::RowVar(rv))) ] .boxed() } diff --git a/hugr-core/src/types/type_row.rs b/hugr-core/src/types/type_row.rs index fa1bb3617..42f5b255a 100644 --- a/hugr-core/src/types/type_row.rs +++ b/hugr-core/src/types/type_row.rs @@ -213,7 +213,7 @@ mod test { use crate::types::{MaybeRV, TypeBase, TypeRowBase}; use ::proptest::prelude::*; - impl Arbitrary for super::super::TypeRowBase where TypeBase: Arbitrary { + impl Arbitrary for super::super::TypeRowBase { type Parameters = RecursionDepth; type Strategy = BoxedStrategy; fn arbitrary_with(depth: Self::Parameters) -> Self::Strategy { From db5e77ef0315c827780d7850410297ebd5c46087 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Thu, 27 Jun 2024 22:55:13 +0100 Subject: [PATCH 096/115] Add #[cfg(test)] fn arb() to MaybeRV, use in impl Arbitrary for TypeBase --- hugr-core/src/types.rs | 30 +++++++++++++++--------------- hugr-core/src/types/type_row.rs | 2 +- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index d37714608..2df12fcb9 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -23,7 +23,7 @@ use itertools::FoldWhile::{Continue, Done}; use itertools::{repeat_n, Itertools}; use serde::{Deserialize, Serialize}; #[cfg(test)] -use {proptest_derive::Arbitrary}; +use {proptest_derive::Arbitrary, proptest::prelude::{any,BoxedStrategy,Strategy}}; use crate::extension::{ExtensionRegistry, SignatureError}; use crate::ops::AliasDecl; @@ -203,7 +203,6 @@ impl From for TypeBase { #[derive( Clone, Debug, Eq, PartialEq, derive_more::Display, serde::Serialize, serde::Deserialize, )] -#[cfg_attr(test, derive(Arbitrary))] #[display(fmt = "{}", "_0")] pub struct RowVariable(usize, TypeBound); @@ -214,6 +213,7 @@ trait MaybeRV: Clone + std::fmt::Debug + std::fmt::Display + From + Eq + P fn validate(&self, var_decls: &[TypeParam]) -> Result<(), SignatureError>; fn substitute(&self, s: &Substitution) -> Vec>; #[cfg(test)] fn weight() -> u32 {1} + #[cfg(test)] fn arb() -> BoxedStrategy; } // Note that I believe the serde derives here are not used except as markers @@ -249,6 +249,11 @@ impl MaybeRV for RowVariable { fn try_from_rv(rv: RowVariable) -> Result { Ok(rv) } + + #[cfg(test)] + fn arb() -> BoxedStrategy { + (any::(), any::()).prop_map(|(i,b)| Self(i,b)).boxed() + } } impl MaybeRV for NoRV { @@ -276,6 +281,11 @@ impl MaybeRV for NoRV { fn weight() -> u32 { 0 } + + #[cfg(test)] + fn arb() -> BoxedStrategy { + any::().prop_map(|_| panic!("Should be ruled out by weight==0")).boxed() + } } #[derive(Clone, Debug, Eq, derive_more::Display)] @@ -708,7 +718,7 @@ pub(crate) mod test { use crate::types::{CustomType, FunctionTypeRV, SumType, TypeRowRV}; use ::proptest::prelude::*; - use super::{AliasDecl, MaybeRV, NoRV, TypeBase, TypeBound, TypeEnum}; + use super::{AliasDecl, MaybeRV, TypeBase, TypeBound, TypeEnum}; impl Arbitrary for super::SumType { type Parameters = RecursionDepth; @@ -724,18 +734,8 @@ pub(crate) mod test { } } } - - impl Arbitrary for NoRV { - type Parameters = (); - - fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy { - panic!("Should be ruled out by weight==0") - } - - type Strategy = BoxedStrategy; - } - impl Arbitrary for TypeBase { + impl Arbitrary for TypeBase { type Parameters = RecursionDepth; type Strategy = BoxedStrategy; fn arbitrary_with(depth: Self::Parameters) -> Self::Strategy { @@ -749,7 +749,7 @@ pub(crate) mod test { 1 => (any::(), any::()).prop_map(|(i,b)| TypeBase::new_var_use(i,b)), // proptest_derive::Arbitrary's weight attribute requires a constant, // rather than this expression, hence the manual impl: - RV::weight() => any::().prop_map(|rv| TypeBase::new(TypeEnum::RowVar(rv))) + RV::weight() => RV::arb().prop_map(|rv| TypeBase::new(TypeEnum::RowVar(rv))) ] .boxed() } diff --git a/hugr-core/src/types/type_row.rs b/hugr-core/src/types/type_row.rs index 42f5b255a..428ac9bcd 100644 --- a/hugr-core/src/types/type_row.rs +++ b/hugr-core/src/types/type_row.rs @@ -213,7 +213,7 @@ mod test { use crate::types::{MaybeRV, TypeBase, TypeRowBase}; use ::proptest::prelude::*; - impl Arbitrary for super::super::TypeRowBase { + impl Arbitrary for super::super::TypeRowBase { type Parameters = RecursionDepth; type Strategy = BoxedStrategy; fn arbitrary_with(depth: Self::Parameters) -> Self::Strategy { From 43f5a089ed85359008af2ab33b9af0b80a6b5d8e Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Mon, 1 Jul 2024 12:26:09 +0100 Subject: [PATCH 097/115] Move stuff into row_var.rs (sealed), fix cargo doc's --- hugr-core/src/types.rs | 97 ++------------------------- hugr-core/src/types/poly_func.rs | 2 +- hugr-core/src/types/row_var.rs | 109 +++++++++++++++++++++++++++++++ hugr-core/src/types/signature.rs | 2 - hugr-core/src/types/type_row.rs | 2 - 5 files changed, 114 insertions(+), 98 deletions(-) create mode 100644 hugr-core/src/types/row_var.rs diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index 2df12fcb9..746e967b5 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -7,6 +7,9 @@ mod serialize; mod signature; pub mod type_param; pub mod type_row; +mod row_var; +pub use row_var::{NoRV, RowVariable}; +use row_var::MaybeRV; pub use crate::ops::constant::{ConstTypeError, CustomCheckFailure}; use crate::types::type_param::check_type_arg; @@ -23,7 +26,7 @@ use itertools::FoldWhile::{Continue, Done}; use itertools::{repeat_n, Itertools}; use serde::{Deserialize, Serialize}; #[cfg(test)] -use {proptest_derive::Arbitrary, proptest::prelude::{any,BoxedStrategy,Strategy}}; +use {proptest_derive::Arbitrary}; use crate::extension::{ExtensionRegistry, SignatureError}; use crate::ops::AliasDecl; @@ -196,98 +199,6 @@ impl From for TypeBase { } } -/// Variable index, and cache of inner TypeBound - matches a [TypeParam::List] of [TypeParam::Type] -/// of this bound (checked in validation) -// Note that I believe the serde derives here are not used except as markers -// so that other types containing this can also #derive-serde the same way. -#[derive( - Clone, Debug, Eq, PartialEq, derive_more::Display, serde::Serialize, serde::Deserialize, -)] -#[display(fmt = "{}", "_0")] -pub struct RowVariable(usize, TypeBound); - -trait MaybeRV: Clone + std::fmt::Debug + std::fmt::Display + From + Eq + PartialEq + 'static { - fn as_rv(&self) -> &RowVariable; - fn try_from_rv(rv: RowVariable) -> Result; - fn bound(&self) -> TypeBound; - fn validate(&self, var_decls: &[TypeParam]) -> Result<(), SignatureError>; - fn substitute(&self, s: &Substitution) -> Vec>; - #[cfg(test)] fn weight() -> u32 {1} - #[cfg(test)] fn arb() -> BoxedStrategy; -} - -// Note that I believe the serde derives here are not used except as markers -// so that other types containing this can also #derive-serde the same way. -#[derive( - Clone, Debug, Eq, PartialEq, derive_more::Display, serde::Serialize, serde::Deserialize, -)] -pub enum NoRV {} - -impl From for RowVariable { - fn from(value: NoRV) -> Self { - match value { } - } -} - -impl MaybeRV for RowVariable { - fn as_rv(&self) -> &RowVariable { - self - } - - fn bound(&self) -> TypeBound { - self.1 - } - - fn validate(&self, var_decls: &[TypeParam]) -> Result<(), SignatureError> { - check_typevar_decl(var_decls, self.0, &TypeParam::new_list(self.1)) - } - - fn substitute(&self, s: &Substitution) -> Vec> { - s.apply_rowvar(self.0, self.1) - } - - fn try_from_rv(rv: RowVariable) -> Result { - Ok(rv) - } - - #[cfg(test)] - fn arb() -> BoxedStrategy { - (any::(), any::()).prop_map(|(i,b)| Self(i,b)).boxed() - } -} - -impl MaybeRV for NoRV { - fn as_rv(&self) -> &RowVariable { - match *self {} - } - - fn bound(&self) -> TypeBound { - match *self {} - } - - fn validate(&self, _var_decls: &[TypeParam]) -> Result<(), SignatureError> { - match *self {} - } - - fn substitute(&self, _s: &Substitution) -> Vec> { - match *self {} - } - - fn try_from_rv(rv: RowVariable) -> Result { - Err(rv) - } - - #[cfg(test)] - fn weight() -> u32 { - 0 - } - - #[cfg(test)] - fn arb() -> BoxedStrategy { - any::().prop_map(|_| panic!("Should be ruled out by weight==0")).boxed() - } -} - #[derive(Clone, Debug, Eq, derive_more::Display)] //#[cfg_attr(test, derive(Arbitrary), proptest(params = "RecursionDepth"))] // handles RowVariable, not NoRV /// Core types diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index 790bf0766..9031be0e5 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -50,7 +50,7 @@ pub type TypeScheme = TypeSchemeBase; /// The polymorphic type of an [OpDef], whose number of input and outputs /// may vary according to how [RowVariable]s therein are instantiated. /// -/// ]OpDef]: crate::extension::OpDef +/// [OpDef]: crate::extension::OpDef pub type TypeSchemeRV = TypeSchemeBase; // deriving Default leads to an impl that only applies for RV: Default diff --git a/hugr-core/src/types/row_var.rs b/hugr-core/src/types/row_var.rs new file mode 100644 index 000000000..adfee562d --- /dev/null +++ b/hugr-core/src/types/row_var.rs @@ -0,0 +1,109 @@ +//! Classes for row variables (i.e. Type variables that can stand for multiple types) + +use crate::extension::SignatureError; +use super::type_param::TypeParam; +use super::{check_typevar_decl, Substitution, TypeBase, TypeBound}; + +#[cfg(test)] +use proptest::prelude::{BoxedStrategy, Strategy, any}; +/// Describes a row variable - a type variable bound with a [TypeParam::List] of [TypeParam::Type] +/// of the specified bound (checked in validation) +// The serde derives here are not used except as markers +// so that other types containing this can also #derive-serde the same way. +#[derive( + Clone, Debug, Eq, PartialEq, derive_more::Display, serde::Serialize, serde::Deserialize, +)] +#[display(fmt = "{}", "_0")] +pub struct RowVariable(pub usize, pub TypeBound); + +// Note that whilst 'pub' this is not re-exported outside private module `row_var` +// so is effectively sealed. +pub trait MaybeRV: Clone + std::fmt::Debug + std::fmt::Display + From + Eq + PartialEq + 'static { + fn as_rv(&self) -> &RowVariable; + fn try_from_rv(rv: RowVariable) -> Result; + fn bound(&self) -> TypeBound; + fn validate(&self, var_decls: &[TypeParam]) -> Result<(), SignatureError>; + #[allow(private_interfaces)] + fn substitute(&self, s: &Substitution) -> Vec>; + #[cfg(test)] fn weight() -> u32 {1} + #[cfg(test)] fn arb() -> BoxedStrategy; +} + +/// Has no instances - used as parameter to [Type] to rule out the possibility +/// of there being any [TypeEnum::RowVar]s +/// +/// [TypeEnum::RowVar]: super::TypeEnum::RowVar +/// [Type]: super::Type +// The serde derives here are not used except as markers +// so that other types containing this can also #derive-serde the same way. +#[derive( + Clone, Debug, Eq, PartialEq, derive_more::Display, serde::Serialize, serde::Deserialize, +)] +pub enum NoRV {} + +impl From for RowVariable { + fn from(value: NoRV) -> Self { + match value { } + } +} + +impl MaybeRV for RowVariable { + fn as_rv(&self) -> &RowVariable { + self + } + + fn bound(&self) -> TypeBound { + self.1 + } + + fn validate(&self, var_decls: &[TypeParam]) -> Result<(), SignatureError> { + check_typevar_decl(var_decls, self.0, &TypeParam::new_list(self.1)) + } + + #[allow(private_interfaces)] + fn substitute(&self, s: &Substitution) -> Vec> { + s.apply_rowvar(self.0, self.1) + } + + fn try_from_rv(rv: RowVariable) -> Result { + Ok(rv) + } + + #[cfg(test)] + fn arb() -> BoxedStrategy { + (any::(), any::()).prop_map(|(i,b)| Self(i,b)).boxed() + } +} + +impl MaybeRV for NoRV { + fn as_rv(&self) -> &RowVariable { + match *self {} + } + + fn bound(&self) -> TypeBound { + match *self {} + } + + fn validate(&self, _var_decls: &[TypeParam]) -> Result<(), SignatureError> { + match *self {} + } + + #[allow(private_interfaces)] + fn substitute(&self, _s: &Substitution) -> Vec> { + match *self {} + } + + fn try_from_rv(rv: RowVariable) -> Result { + Err(rv) + } + + #[cfg(test)] + fn weight() -> u32 { + 0 + } + + #[cfg(test)] + fn arb() -> BoxedStrategy { + any::().prop_map(|_| panic!("Should be ruled out by weight==0")).boxed() + } +} diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index b903c5e52..4c78b86e1 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -41,8 +41,6 @@ pub type FunctionType = FuncTypeBase; /// A function that may contain [RowVariable]s and thus has potentially-unknown arity; /// passable as a value round a Hugr (see [Type::new_function]) but not a valid node type. -/// -/// [RowVariable]: crate::types::TypeEnum::RowVariable pub type FunctionTypeRV = FuncTypeBase; impl FuncTypeBase { diff --git a/hugr-core/src/types/type_row.rs b/hugr-core/src/types/type_row.rs index 428ac9bcd..44ad018c0 100644 --- a/hugr-core/src/types/type_row.rs +++ b/hugr-core/src/types/type_row.rs @@ -17,8 +17,6 @@ use itertools::Itertools; /// List of types, used for function signatures. /// The `ROWVARS` parameter controls whether this may contain [RowVariable]s -/// -/// [RowVariable]: crate::types::TypeEnum::RowVariable #[derive(Clone, Eq, Debug, serde::Serialize, serde::Deserialize)] #[non_exhaustive] #[serde(transparent)] From 270675b51e787525e2da9b4a93311f03d4ea13e4 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Mon, 1 Jul 2024 12:32:51 +0100 Subject: [PATCH 098/115] make MaybeRV require Into as well as From --- hugr-core/src/types/row_var.rs | 2 +- hugr-core/src/types/type_row.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/hugr-core/src/types/row_var.rs b/hugr-core/src/types/row_var.rs index adfee562d..3389e47ad 100644 --- a/hugr-core/src/types/row_var.rs +++ b/hugr-core/src/types/row_var.rs @@ -18,7 +18,7 @@ pub struct RowVariable(pub usize, pub TypeBound); // Note that whilst 'pub' this is not re-exported outside private module `row_var` // so is effectively sealed. -pub trait MaybeRV: Clone + std::fmt::Debug + std::fmt::Display + From + Eq + PartialEq + 'static { +pub trait MaybeRV: Clone + std::fmt::Debug + std::fmt::Display + From + Into + Eq + PartialEq + 'static { fn as_rv(&self) -> &RowVariable; fn try_from_rv(rv: RowVariable) -> Result; fn bound(&self) -> TypeBound; diff --git a/hugr-core/src/types/type_row.rs b/hugr-core/src/types/type_row.rs index 44ad018c0..d6f0e0977 100644 --- a/hugr-core/src/types/type_row.rs +++ b/hugr-core/src/types/type_row.rs @@ -174,7 +174,7 @@ impl From<&'static [TypeBase]> for TypeRowBase { } } -impl> From> for TypeRowRV { +impl From> for TypeRowRV { fn from(t: TypeBase) -> Self { Self { types: vec![t.into_()].into(), From 0297d7c2ff2821053f19fea057d8be9b27ff1327 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Mon, 1 Jul 2024 12:34:52 +0100 Subject: [PATCH 099/115] Remove commented-out derive --- hugr-core/src/types.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index 746e967b5..4f19d3de5 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -200,7 +200,6 @@ impl From for TypeBase { } #[derive(Clone, Debug, Eq, derive_more::Display)] -//#[cfg_attr(test, derive(Arbitrary), proptest(params = "RecursionDepth"))] // handles RowVariable, not NoRV /// Core types pub enum TypeEnum { // TODO optimise with Box ? From af0f818e007aec8436ccd091314a40d6f626bf96 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Mon, 1 Jul 2024 12:35:06 +0100 Subject: [PATCH 100/115] Missed PolyFuncType -> TypeSchemeBase --- hugr-core/src/types/poly_func.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index 9031be0e5..3b4597d4c 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -79,7 +79,7 @@ impl From for TypeSchemeRV { } impl TryFrom> for FuncTypeBase { - /// If the PolyFuncType is not monomorphic, fail with its binders + /// If the TypeSchemeBase is not monomorphic, fail with its binders type Error = Vec; fn try_from(value: TypeSchemeBase) -> Result { From aa54aff3ace96635c598af3f3746971481634a0c Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Mon, 1 Jul 2024 12:50:25 +0100 Subject: [PATCH 101/115] Remove try_into_ via TryFrom --- hugr-core/src/types.rs | 18 ++++++------------ hugr-core/src/types/type_param.rs | 14 ++++++++++---- hugr-core/src/types/type_row.rs | 3 ++- 3 files changed, 18 insertions(+), 17 deletions(-) diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index 4f19d3de5..771753ed3 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -464,10 +464,11 @@ impl TypeRV { } // ====== Conversions ====== -impl TypeBase { - fn try_into_(self) -> Result { - Ok(TypeBase( - match self.0 { +impl TryFrom for Type { + type Error = RowVariable; + fn try_from(value: TypeRV) -> Result { + Ok(Self( + match value.0 { TypeEnum::Extension(e) => TypeEnum::Extension(e), TypeEnum::Alias(a) => TypeEnum::Alias(a), TypeEnum::Function(f) => TypeEnum::Function(f), @@ -475,7 +476,7 @@ impl TypeBase { TypeEnum::RowVar(rv) => {return Err(rv.as_rv().clone())}, TypeEnum::Sum(s) => TypeEnum::Sum(s), }, - self.1, + value.1, )) } } @@ -503,13 +504,6 @@ impl From for TypeRV { } } -impl TryFrom for Type { - type Error = SignatureError; - fn try_from(value: TypeRV) -> Result { - value.try_into_().map_err(|var| SignatureError::RowVarWhereTypeExpected { var }) - } -} - /// Details a replacement of type variables with a finite list of known values. /// (Variables out of the range of the list will result in a panic) pub(crate) struct Substitution<'a>(&'a [TypeArg], &'a ExtensionRegistry); diff --git a/hugr-core/src/types/type_param.rs b/hugr-core/src/types/type_param.rs index 9e9cc9a73..e2901ee01 100644 --- a/hugr-core/src/types/type_param.rs +++ b/hugr-core/src/types/type_param.rs @@ -14,7 +14,7 @@ use crate::extension::ExtensionRegistry; use crate::extension::ExtensionSet; use crate::extension::SignatureError; -use super::{check_typevar_decl, CustomType, MaybeRV, RowVariable, Substitution, Type, TypeBase, TypeBound}; +use super::{check_typevar_decl, CustomType, RowVariable, Substitution, Type, TypeBound, TypeRV}; /// The upper non-inclusive bound of a [`TypeParam::BoundedNat`] // A None inner value implies the maximum bound: u64::MAX + 1 (all u64 values valid) @@ -183,9 +183,15 @@ pub enum TypeArg { }, } -impl From> for TypeArg { - fn from(ty: TypeBase) -> Self { - match ty.try_into_() { +impl From for TypeArg { + fn from(ty: Type) -> Self { + TypeArg::Type {ty} + } +} + +impl From for TypeArg { + fn from(value: TypeRV) -> Self { + match value.try_into() { Ok(ty) => TypeArg::Type {ty}, Err(RowVariable(idx, bound)) => TypeArg::new_var_use(idx, TypeParam::new_list(bound)) diff --git a/hugr-core/src/types/type_row.rs b/hugr-core/src/types/type_row.rs index d6f0e0977..1931b6983 100644 --- a/hugr-core/src/types/type_row.rs +++ b/hugr-core/src/types/type_row.rs @@ -131,7 +131,8 @@ impl TryFrom for TypeRow { .into_owned() .into_iter() .map(|t| t.try_into()) - .collect::, _>>()?, + .collect::, _>>() + .map_err(|var| SignatureError::RowVarWhereTypeExpected { var })? )) } } From 3270b938e4bf1329c05fff8c4e5ee5ee16fbe6ee Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Mon, 1 Jul 2024 12:52:41 +0100 Subject: [PATCH 102/115] find_rowvar via try_from, at cost of extra clone --- hugr-core/src/types/signature.rs | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index 4c78b86e1..1ad0d49c7 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -6,7 +6,7 @@ use std::fmt::{self, Display, Write}; use super::type_param::TypeParam; use super::type_row::TypeRowBase; -use super::{MaybeRV, NoRV, RowVariable, Substitution, Type, TypeEnum, TypeRow}; +use super::{MaybeRV, NoRV, RowVariable, Substitution, Type, TypeRow}; use crate::core::PortIndex; use crate::extension::{ExtensionRegistry, ExtensionSet, SignatureError}; @@ -105,15 +105,12 @@ impl FuncTypeBase { } impl FunctionTypeRV { - /// If this FunctionType contains any row variables, return one. + /// If this FunctionTypeRV contains any row variables, return one. pub fn find_rowvar(&self) -> Option { self.input .iter() .chain(self.output.iter()) - .find_map(|t| match &t.0 { - TypeEnum::RowVar(rv) => Some(rv.clone()), - _ => None, - }) + .find_map(|t| Type::try_from(t.clone()).err()) } } From eff09077533ea02bed0e99ff9ed7540bb6dc0e50 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Mon, 1 Jul 2024 13:00:08 +0100 Subject: [PATCH 103/115] fmt --- hugr-core/src/types.rs | 28 +++++++++++++------------ hugr-core/src/types/poly_func.rs | 9 +++++--- hugr-core/src/types/row_var.rs | 35 +++++++++++++++++++++++-------- hugr-core/src/types/serialize.rs | 8 +++---- hugr-core/src/types/signature.rs | 8 +++++-- hugr-core/src/types/type_param.rs | 7 +++---- hugr-core/src/types/type_row.rs | 2 +- 7 files changed, 61 insertions(+), 36 deletions(-) diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index 771753ed3..fb2416eb0 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -3,13 +3,13 @@ mod check; pub mod custom; mod poly_func; +mod row_var; mod serialize; mod signature; pub mod type_param; pub mod type_row; -mod row_var; -pub use row_var::{NoRV, RowVariable}; use row_var::MaybeRV; +pub use row_var::{NoRV, RowVariable}; pub use crate::ops::constant::{ConstTypeError, CustomCheckFailure}; use crate::types::type_param::check_type_arg; @@ -24,9 +24,9 @@ pub use type_row::{TypeRow, TypeRowRV}; use itertools::FoldWhile::{Continue, Done}; use itertools::{repeat_n, Itertools}; -use serde::{Deserialize, Serialize}; #[cfg(test)] -use {proptest_derive::Arbitrary}; +use proptest_derive::Arbitrary; +use serde::{Deserialize, Serialize}; use crate::extension::{ExtensionRegistry, SignatureError}; use crate::ops::AliasDecl; @@ -205,15 +205,13 @@ pub enum TypeEnum { // TODO optimise with Box ? // or some static version of this? #[allow(missing_docs)] - Extension(CustomType,), + Extension(CustomType), #[allow(missing_docs)] #[display(fmt = "Alias({})", "_0.name()")] Alias(AliasDecl), #[allow(missing_docs)] #[display(fmt = "Function({})", "_0")] - Function( - Box, - ), + Function(Box), // Index into TypeParams, and cache of TypeBound (checked in validation) #[allow(missing_docs)] #[display(fmt = "Variable({})", _0)] @@ -473,7 +471,7 @@ impl TryFrom for Type { TypeEnum::Alias(a) => TypeEnum::Alias(a), TypeEnum::Function(f) => TypeEnum::Function(f), TypeEnum::Variable(idx, bound) => TypeEnum::Variable(idx, bound), - TypeEnum::RowVar(rv) => {return Err(rv.as_rv().clone())}, + TypeEnum::RowVar(rv) => return Err(rv.as_rv().clone()), TypeEnum::Sum(s) => TypeEnum::Sum(s), }, value.1, @@ -484,7 +482,10 @@ impl TryFrom for Type { impl TypeBase { /// A swiss-army-knife for any safe conversion of the type argument `RV1` /// to/from [NoRV]/RowVariable/rust-type-variable. - fn into_(self) -> TypeBase where RV1: Into { + fn into_(self) -> TypeBase + where + RV1: Into, + { TypeBase( match self.0 { TypeEnum::Extension(e) => TypeEnum::Extension(e), @@ -493,7 +494,8 @@ impl TypeBase { TypeEnum::Variable(idx, bound) => TypeEnum::Variable(idx, bound), TypeEnum::RowVar(rv) => TypeEnum::RowVar(rv.into()), TypeEnum::Sum(s) => TypeEnum::Sum(s), - }, self.1 + }, + self.1, ) } } @@ -620,9 +622,9 @@ pub(crate) mod test { use crate::proptest::RecursionDepth; + use super::{AliasDecl, MaybeRV, TypeBase, TypeBound, TypeEnum}; use crate::types::{CustomType, FunctionTypeRV, SumType, TypeRowRV}; use ::proptest::prelude::*; - use super::{AliasDecl, MaybeRV, TypeBase, TypeBound, TypeEnum}; impl Arbitrary for super::SumType { type Parameters = RecursionDepth; @@ -638,7 +640,7 @@ pub(crate) mod test { } } } - + impl Arbitrary for TypeBase { type Parameters = RecursionDepth; type Strategy = BoxedStrategy; diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index 3b4597d4c..ff4868e49 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -9,9 +9,9 @@ use { proptest_derive::Arbitrary, }; -use super::{signature::FuncTypeBase, MaybeRV, NoRV, RowVariable}; use super::type_param::{check_type_args, TypeArg, TypeParam}; use super::Substitution; +use super::{signature::FuncTypeBase, MaybeRV, NoRV, RowVariable}; /// A polymorphic type scheme, i.e. of a [FuncDecl], [FuncDefn] or [OpDef]. /// (Nodes/operations in the Hugr are not polymorphic.) @@ -56,7 +56,10 @@ pub type TypeSchemeRV = TypeSchemeBase; // deriving Default leads to an impl that only applies for RV: Default impl Default for TypeSchemeBase { fn default() -> Self { - Self { params: Default::default(), body: Default::default() } + Self { + params: Default::default(), + body: Default::default(), + } } } @@ -152,7 +155,7 @@ pub(crate) mod test { use crate::types::signature::FuncTypeBase; use crate::types::type_param::{TypeArg, TypeArgError, TypeParam}; use crate::types::{ - CustomType, FunctionType, FunctionTypeRV, MaybeRV, Type, TypeBound, TypeName, TypeRV + CustomType, FunctionType, FunctionTypeRV, MaybeRV, Type, TypeBound, TypeName, TypeRV, }; use crate::Extension; diff --git a/hugr-core/src/types/row_var.rs b/hugr-core/src/types/row_var.rs index 3389e47ad..9efc2e12f 100644 --- a/hugr-core/src/types/row_var.rs +++ b/hugr-core/src/types/row_var.rs @@ -1,11 +1,11 @@ //! Classes for row variables (i.e. Type variables that can stand for multiple types) -use crate::extension::SignatureError; use super::type_param::TypeParam; use super::{check_typevar_decl, Substitution, TypeBase, TypeBound}; +use crate::extension::SignatureError; #[cfg(test)] -use proptest::prelude::{BoxedStrategy, Strategy, any}; +use proptest::prelude::{any, BoxedStrategy, Strategy}; /// Describes a row variable - a type variable bound with a [TypeParam::List] of [TypeParam::Type] /// of the specified bound (checked in validation) // The serde derives here are not used except as markers @@ -18,20 +18,33 @@ pub struct RowVariable(pub usize, pub TypeBound); // Note that whilst 'pub' this is not re-exported outside private module `row_var` // so is effectively sealed. -pub trait MaybeRV: Clone + std::fmt::Debug + std::fmt::Display + From + Into + Eq + PartialEq + 'static { +pub trait MaybeRV: + Clone + + std::fmt::Debug + + std::fmt::Display + + From + + Into + + Eq + + PartialEq + + 'static +{ fn as_rv(&self) -> &RowVariable; fn try_from_rv(rv: RowVariable) -> Result; fn bound(&self) -> TypeBound; fn validate(&self, var_decls: &[TypeParam]) -> Result<(), SignatureError>; #[allow(private_interfaces)] fn substitute(&self, s: &Substitution) -> Vec>; - #[cfg(test)] fn weight() -> u32 {1} - #[cfg(test)] fn arb() -> BoxedStrategy; + #[cfg(test)] + fn weight() -> u32 { + 1 + } + #[cfg(test)] + fn arb() -> BoxedStrategy; } /// Has no instances - used as parameter to [Type] to rule out the possibility /// of there being any [TypeEnum::RowVar]s -/// +/// /// [TypeEnum::RowVar]: super::TypeEnum::RowVar /// [Type]: super::Type // The serde derives here are not used except as markers @@ -43,7 +56,7 @@ pub enum NoRV {} impl From for RowVariable { fn from(value: NoRV) -> Self { - match value { } + match value {} } } @@ -71,7 +84,9 @@ impl MaybeRV for RowVariable { #[cfg(test)] fn arb() -> BoxedStrategy { - (any::(), any::()).prop_map(|(i,b)| Self(i,b)).boxed() + (any::(), any::()) + .prop_map(|(i, b)| Self(i, b)) + .boxed() } } @@ -104,6 +119,8 @@ impl MaybeRV for NoRV { #[cfg(test)] fn arb() -> BoxedStrategy { - any::().prop_map(|_| panic!("Should be ruled out by weight==0")).boxed() + any::() + .prop_map(|_| panic!("Should be ruled out by weight==0")) + .boxed() } } diff --git a/hugr-core/src/types/serialize.rs b/hugr-core/src/types/serialize.rs index 622344ea4..82af291a1 100644 --- a/hugr-core/src/types/serialize.rs +++ b/hugr-core/src/types/serialize.rs @@ -59,10 +59,10 @@ impl TryFrom for TypeBase { SerSimpleType::Alias(a) => TypeBase::new_alias(a), SerSimpleType::V { i, b } => TypeBase::new_var_use(i, b), // We can't use new_row_var because that returns Type not Type. - SerSimpleType::R { i, b } => { - TypeBase::new(TypeEnum::RowVar(RV::try_from_rv(RowVariable(i, b)) - .map_err(|var| SignatureError::RowVarWhereTypeExpected { var })?)) - } + SerSimpleType::R { i, b } => TypeBase::new(TypeEnum::RowVar( + RV::try_from_rv(RowVariable(i, b)) + .map_err(|var| SignatureError::RowVarWhereTypeExpected { var })?, + )), }) } } diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index 1ad0d49c7..463d3e34c 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -115,9 +115,13 @@ impl FunctionTypeRV { } // deriving Default leads to an impl that only applies for RV: Default -impl Default for FuncTypeBase { +impl Default for FuncTypeBase { fn default() -> Self { - Self { input: Default::default(), output: Default::default(), extension_reqs: Default::default() } + Self { + input: Default::default(), + output: Default::default(), + extension_reqs: Default::default(), + } } } diff --git a/hugr-core/src/types/type_param.rs b/hugr-core/src/types/type_param.rs index e2901ee01..c59411604 100644 --- a/hugr-core/src/types/type_param.rs +++ b/hugr-core/src/types/type_param.rs @@ -185,16 +185,15 @@ pub enum TypeArg { impl From for TypeArg { fn from(ty: Type) -> Self { - TypeArg::Type {ty} + TypeArg::Type { ty } } } impl From for TypeArg { fn from(value: TypeRV) -> Self { match value.try_into() { - Ok(ty) => TypeArg::Type {ty}, - Err(RowVariable(idx, bound)) => - TypeArg::new_var_use(idx, TypeParam::new_list(bound)) + Ok(ty) => TypeArg::Type { ty }, + Err(RowVariable(idx, bound)) => TypeArg::new_var_use(idx, TypeParam::new_list(bound)), } } } diff --git a/hugr-core/src/types/type_row.rs b/hugr-core/src/types/type_row.rs index 1931b6983..ec510fc28 100644 --- a/hugr-core/src/types/type_row.rs +++ b/hugr-core/src/types/type_row.rs @@ -132,7 +132,7 @@ impl TryFrom for TypeRow { .into_iter() .map(|t| t.try_into()) .collect::, _>>() - .map_err(|var| SignatureError::RowVarWhereTypeExpected { var })? + .map_err(|var| SignatureError::RowVarWhereTypeExpected { var })?, )) } } From 23db41da558a5ba697cd88f239659e91eb3ce655 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Mon, 15 Jul 2024 09:44:19 +0100 Subject: [PATCH 104/115] remove type annots, fix doclinks, various comments --- hugr-core/src/extension/op_def.rs | 2 +- hugr-core/src/extension/prelude.rs | 2 +- hugr-core/src/extension/type_def.rs | 4 ++-- hugr-core/src/hugr/serialize/test.rs | 4 ++-- hugr-core/src/hugr/validate.rs | 5 +---- hugr-core/src/ops/constant.rs | 6 +++--- hugr-core/src/types.rs | 5 ++--- hugr-core/src/types/poly_func.rs | 8 ++++---- hugr-core/src/types/serialize.rs | 2 +- hugr-core/src/types/signature.rs | 21 +++++++++++++-------- hugr-core/src/types/type_param.rs | 6 +++--- hugr/benches/benchmarks/types.rs | 4 ++-- 12 files changed, 35 insertions(+), 34 deletions(-) diff --git a/hugr-core/src/extension/op_def.rs b/hugr-core/src/extension/op_def.rs index 867792e18..c0e0f9533 100644 --- a/hugr-core/src/extension/op_def.rs +++ b/hugr-core/src/extension/op_def.rs @@ -235,7 +235,7 @@ impl SignatureFunc { args: &[TypeArg], exts: &ExtensionRegistry, ) -> Result { - let temp: TypeSchemeRV; + let temp: TypeSchemeRV; // to keep alive let (pf, args) = match &self { SignatureFunc::TypeScheme(custom) => { custom.validate.validate(args, def, exts)?; diff --git a/hugr-core/src/extension/prelude.rs b/hugr-core/src/extension/prelude.rs index c96b9194f..c82a7a8be 100644 --- a/hugr-core/src/extension/prelude.rs +++ b/hugr-core/src/extension/prelude.rs @@ -436,7 +436,7 @@ mod test { .instantiate([]) .unwrap(); - let ext_type: Type = Type::new_extension(ext_def); + let ext_type = Type::new_extension(ext_def); assert_eq!(ext_type, ERROR_TYPE); let error_val = ConstError::new(2, "my message"); diff --git a/hugr-core/src/extension/type_def.rs b/hugr-core/src/extension/type_def.rs index 7f03f69b3..68b4ec3e0 100644 --- a/hugr-core/src/extension/type_def.rs +++ b/hugr-core/src/extension/type_def.rs @@ -182,14 +182,14 @@ mod test { description: "Some parametrised type".into(), bound: TypeDefBound::FromParams(vec![0]), }; - let typ: Type = Type::new_extension( + let typ = Type::new_extension( def.instantiate(vec![TypeArg::Type { ty: Type::new_function(FunctionType::new(vec![], vec![])), }]) .unwrap(), ); assert_eq!(typ.least_upper_bound(), TypeBound::Copyable); - let typ2: Type = 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::Eq); // And some bad arguments...firstly, wrong kind of TypeArg: diff --git a/hugr-core/src/hugr/serialize/test.rs b/hugr-core/src/hugr/serialize/test.rs index 2f9c771d5..0e5340831 100644 --- a/hugr-core/src/hugr/serialize/test.rs +++ b/hugr-core/src/hugr/serialize/test.rs @@ -381,7 +381,7 @@ fn constants_roundtrip() -> Result<(), Box> { #[test] fn serialize_types_roundtrip() { - let g = Type::new_function(FunctionType::new_endo(vec![])); + let g: Type = Type::new_function(FunctionType::new_endo(vec![])); check_testing_roundtrip(g.clone()); // A Simple tuple @@ -392,7 +392,7 @@ fn serialize_types_roundtrip() { let t = TypeRV::new_sum([type_row![USIZE_T], type_row![FLOAT64_TYPE]]); check_testing_roundtrip(t); - let t: Type = Type::new_unit_sum(4); + let t = Type::new_unit_sum(4); check_testing_roundtrip(t); } diff --git a/hugr-core/src/hugr/validate.rs b/hugr-core/src/hugr/validate.rs index 1e7104e4e..c8c0b5959 100644 --- a/hugr-core/src/hugr/validate.rs +++ b/hugr-core/src/hugr/validate.rs @@ -298,11 +298,8 @@ impl<'a, 'b> ValidationContext<'a, 'b> { match &port_kind { EdgeKind::Value(ty) => ty.validate(self.extension_registry, var_decls), // Static edges must *not* refer to type variables declared by enclosing FuncDefns - // as these are only types at runtime. (Note the choice of `allow_row_vars` as `false` is arbitrary here.) + // as these are only types at runtime. EdgeKind::Const(ty) => ty.validate(self.extension_registry, &[]), - // Allow function "value" to have unknown arity. A Call node will have to provide - // TypeArgs that produce a known arity, but a LoadFunction might pass the function - // value ("function pointer") around without knowing how to call it. EdgeKind::Function(pf) => pf.validate(self.extension_registry), _ => Ok(()), } diff --git a/hugr-core/src/ops/constant.rs b/hugr-core/src/ops/constant.rs index 40be64221..dc4ea733a 100644 --- a/hugr-core/src/ops/constant.rs +++ b/hugr-core/src/ops/constant.rs @@ -593,7 +593,7 @@ mod test { fn function_value(simple_dfg_hugr: Hugr) { let v = Value::function(simple_dfg_hugr).unwrap(); - let correct_type: Type = Type::new_function(FunctionType::new_endo(type_row![ + let correct_type = Type::new_function(FunctionType::new_endo(type_row![ crate::extension::prelude::BOOL_T ])); @@ -652,12 +652,12 @@ mod test { let yaml_const: Value = CustomSerialized::new(typ_int.clone(), YamlValue::Number(6.into()), ex_id.clone()) .into(); - let classic_t: Type = Type::new_extension(typ_int.clone()); + let classic_t = Type::new_extension(typ_int.clone()); assert_matches!(classic_t.least_upper_bound(), TypeBound::Eq); assert_eq!(yaml_const.get_type(), classic_t); let typ_qb = CustomType::new("my_type", vec![], ex_id, TypeBound::Eq); - let t: Type = Type::new_extension(typ_qb.clone()); + let t = Type::new_extension(typ_qb.clone()); assert_ne!(yaml_const.get_type(), t); } diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index fb2416eb0..5cba5293e 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -50,7 +50,7 @@ pub enum EdgeKind { Value(Type), /// A reference to a static constant value - must be a Copyable type Const(Type), - /// A reference to a function i.e. [FuncDecl] or [FuncDefn] + /// A reference to a function i.e. [FuncDecl] or [FuncDefn]. /// /// [FuncDecl]: crate::ops::FuncDecl /// [FuncDefn]: crate::ops::FuncDefn @@ -259,7 +259,7 @@ impl TypeEnum { /// # use hugr::types::{Type, TypeBound}; /// # use hugr::type_row; /// -/// let sum: Type = Type::new_sum([type_row![], type_row![]]); +/// let sum = Type::new_sum([type_row![], type_row![]]); /// assert_eq!(sum.least_upper_bound(), TypeBound::Eq); /// ``` /// @@ -614,7 +614,6 @@ pub(crate) mod test { assert_eq!(pred1, pred2); let pred_direct = SumType::Unit { size: 2 }; - // Pick arbitrarily assert_eq!(pred1, Type::from(pred_direct)); } diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index ff4868e49..cc9774d15 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -28,15 +28,15 @@ use super::{signature::FuncTypeBase, MaybeRV, NoRV, RowVariable}; "params.iter().map(ToString::to_string).join(\" \")", "body" )] -pub struct TypeSchemeBase { +pub struct TypeSchemeBase { /// The declared type parameters, i.e., these must be instantiated with /// the same number of [TypeArg]s before the function can be called. This /// defines the indices used by variables inside the body. #[cfg_attr(test, proptest(strategy = "vec(any_with::(params), 0..3)"))] params: Vec, /// Template for the function. May contain variables up to length of [Self::params] - #[cfg_attr(test, proptest(strategy = "any_with::>(params)"))] - body: FuncTypeBase, + #[cfg_attr(test, proptest(strategy = "any_with::>(params)"))] + body: FuncTypeBase, } /// The polymorphic type of a [Call]-able function ([FuncDecl] or [FuncDefn]). @@ -106,7 +106,7 @@ impl TypeSchemeBase { } /// Create a new TypeSchemeBase given the kinds of the variables it declares - /// and the underlying function type. + /// and the underlying [FuncTypeBase]. pub fn new(params: impl Into>, body: impl Into>) -> Self { Self { params: params.into(), diff --git a/hugr-core/src/types/serialize.rs b/hugr-core/src/types/serialize.rs index 82af291a1..c557a1e86 100644 --- a/hugr-core/src/types/serialize.rs +++ b/hugr-core/src/types/serialize.rs @@ -58,7 +58,7 @@ impl TryFrom for TypeBase { SerSimpleType::Opaque(o) => TypeBase::new_extension(o), SerSimpleType::Alias(a) => TypeBase::new_alias(a), SerSimpleType::V { i, b } => TypeBase::new_var_use(i, b), - // We can't use new_row_var because that returns Type not Type. + // We can't use new_row_var because that returns TypeRV not TypeBase. SerSimpleType::R { i, b } => TypeBase::new(TypeEnum::RowVar( RV::try_from_rv(RowVariable(i, b)) .map_err(|var| SignatureError::RowVarWhereTypeExpected { var })?, diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index 463d3e34c..78de0d716 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -17,13 +17,13 @@ use {crate::proptest::RecursionDepth, ::proptest::prelude::*, proptest_derive::A #[derive(Clone, Debug, Eq, serde::Serialize, serde::Deserialize)] #[cfg_attr(test, derive(Arbitrary), proptest(params = "RecursionDepth"))] -/// Describes the edges required to/from a node (when ROWVARS=false); -/// or (when ROWVARS=true) the type of a [Graph] or the inputs/outputs from an OpDef +/// Describes the edges required to/from a node or inside a [FuncDefn] (when ROWVARS=[NoRV]); +/// or (when ROWVARS=[RowVariable]) the type of a higher-order [function value] or the inputs/outputs from an OpDef /// /// ROWVARS specifies whether it may contain [RowVariable]s or not. /// -/// [Graph]: crate::ops::constant::Value::Function -/// [RowVariable]: crate::types::TypeEnum::RowVariable +/// [function value]: crate::ops::constant::Value::Function +/// [FuncDefn]: crate::ops::FuncDefn pub struct FuncTypeBase { /// Value inputs of the function. #[cfg_attr(test, proptest(strategy = "any_with::>(params)"))] @@ -35,12 +35,17 @@ pub struct FuncTypeBase { pub extension_reqs: ExtensionSet, } -/// The concept of "signature" in the spec - the edges required to/from a node or graph -/// and also the target (value) of a call (static). +/// The concept of "signature" in the spec - the edges required to/from a node +/// or within a [FuncDefn], also the target (value) of a call (static). +/// +/// [FuncDefn]: crate::ops::FuncDefn pub type FunctionType = FuncTypeBase; /// A function that may contain [RowVariable]s and thus has potentially-unknown arity; -/// passable as a value round a Hugr (see [Type::new_function]) but not a valid node type. +/// used for [OpDef]'s and passable as a value round a Hugr (see [Type::new_function]) +/// but not a valid node type. +/// +/// [OpDef]: crate::extension::OpDef pub type FunctionTypeRV = FuncTypeBase; impl FuncTypeBase { @@ -63,7 +68,7 @@ impl FuncTypeBase { Self { input: input.into(), output: output.into(), - extension_reqs: ExtensionSet::default(), + extension_reqs: ExtensionSet::new(), } } diff --git a/hugr-core/src/types/type_param.rs b/hugr-core/src/types/type_param.rs index 94d90fb16..1e517c0a1 100644 --- a/hugr-core/src/types/type_param.rs +++ b/hugr-core/src/types/type_param.rs @@ -46,11 +46,11 @@ impl UpperBound { } } -/// A *kind* of [TypeArg]. Thus, a parameter declared by a [TypeSchemeRV] (e.g. [OpDef]), -/// specifying a value that may (resp. must) be provided to instantiate it. +/// A *kind* of [TypeArg]. Thus, a parameter declared by a [TypeScheme] or [TypeSchemeRV], +/// specifying a value that must be provided statically in order to instantiate it. /// +/// [TypeScheme]: super::TypeScheme /// [TypeSchemeRV]: super::TypeSchemeRV -/// [OpDef]: crate::extension::OpDef #[derive( Clone, Debug, PartialEq, Eq, derive_more::Display, serde::Deserialize, serde::Serialize, )] diff --git a/hugr/benches/benchmarks/types.rs b/hugr/benches/benchmarks/types.rs index 3698a2aed..5362511aa 100644 --- a/hugr/benches/benchmarks/types.rs +++ b/hugr/benches/benchmarks/types.rs @@ -10,10 +10,10 @@ use criterion::{black_box, criterion_group, AxisScale, Criterion, PlotConfigurat fn make_complex_type() -> Type { let qb = QB_T; let int = USIZE_T; - let q_register: Type = Type::new_tuple(vec![qb; 8]); + 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)); - let sum: Type = Type::new_sum([q_register, q_alias]); + let sum = Type::new_sum([q_register, q_alias]); Type::new_function(FunctionType::new(vec![sum], vec![b_register])) } From 3245b45f2a2e4a08636b912ff80fb2216a1275b7 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Mon, 15 Jul 2024 10:12:51 +0100 Subject: [PATCH 105/115] fmt --- hugr-core/src/types/signature.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index 78de0d716..5f56be41e 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -37,14 +37,14 @@ pub struct FuncTypeBase { /// The concept of "signature" in the spec - the edges required to/from a node /// or within a [FuncDefn], also the target (value) of a call (static). -/// +/// /// [FuncDefn]: crate::ops::FuncDefn pub type FunctionType = FuncTypeBase; /// A function that may contain [RowVariable]s and thus has potentially-unknown arity; /// used for [OpDef]'s and passable as a value round a Hugr (see [Type::new_function]) /// but not a valid node type. -/// +/// /// [OpDef]: crate::extension::OpDef pub type FunctionTypeRV = FuncTypeBase; From eb3e86cc2946a57e1c83ca4faf5fe57924358755 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 16 Jul 2024 10:14:57 +0100 Subject: [PATCH 106/115] TypeScheme(RV/Base) back to PolyFuncType(RV/Base) --- hugr-core/src/builder.rs | 4 +- hugr-core/src/builder/build_traits.rs | 4 +- hugr-core/src/builder/dataflow.rs | 6 +- hugr-core/src/builder/module.rs | 4 +- .../src/extension/declarative/signature.rs | 4 +- hugr-core/src/extension/op_def.rs | 82 +++++++++---------- hugr-core/src/extension/prelude.rs | 8 +- hugr-core/src/hugr/serialize/test.rs | 50 +++++------ hugr-core/src/hugr/validate/test.rs | 28 +++---- hugr-core/src/hugr/views.rs | 4 +- hugr-core/src/ops/dataflow.rs | 14 ++-- hugr-core/src/ops/module.rs | 6 +- .../std_extensions/arithmetic/conversions.rs | 4 +- .../src/std_extensions/arithmetic/int_ops.rs | 12 +-- hugr-core/src/std_extensions/collections.rs | 6 +- hugr-core/src/std_extensions/logic.rs | 2 +- hugr-core/src/types.rs | 4 +- hugr-core/src/types/poly_func.rs | 50 +++++------ hugr-core/src/types/type_param.rs | 6 +- hugr-core/src/utils.rs | 6 +- hugr/src/lib.rs | 6 +- 21 files changed, 155 insertions(+), 155 deletions(-) diff --git a/hugr-core/src/builder.rs b/hugr-core/src/builder.rs index 0516ecd66..57fff12e2 100644 --- a/hugr-core/src/builder.rs +++ b/hugr-core/src/builder.rs @@ -235,7 +235,7 @@ pub(crate) mod test { use crate::hugr::{views::HugrView, HugrMut}; use crate::ops; use crate::std_extensions::arithmetic::float_ops::FLOAT_OPS_REGISTRY; - use crate::types::{FunctionType, Type, TypeScheme}; + use crate::types::{FunctionType, PolyFuncType, Type}; use crate::{type_row, Hugr}; use super::handle::BuildHandle; @@ -258,7 +258,7 @@ pub(crate) mod test { } pub(super) fn build_main( - signature: TypeScheme, + signature: PolyFuncType, f: impl FnOnce(FunctionBuilder<&mut Hugr>) -> Result>, BuildError>, ) -> Result { let mut module_builder = ModuleBuilder::new(); diff --git a/hugr-core/src/builder/build_traits.rs b/hugr-core/src/builder/build_traits.rs index bee193735..62cd84cf1 100644 --- a/hugr-core/src/builder/build_traits.rs +++ b/hugr-core/src/builder/build_traits.rs @@ -19,7 +19,7 @@ use crate::{ }; use crate::extension::{ExtensionRegistry, ExtensionSet, PRELUDE_REGISTRY, TO_BE_INFERRED}; -use crate::types::{FunctionType, Type, TypeArg, TypeRow, TypeScheme}; +use crate::types::{FunctionType, PolyFuncType, Type, TypeArg, TypeRow}; use itertools::Itertools; @@ -78,7 +78,7 @@ pub trait Container { fn define_function( &mut self, name: impl Into, - signature: impl Into, + signature: impl Into, ) -> Result, BuildError> { let signature = signature.into(); let body = signature.body().clone(); diff --git a/hugr-core/src/builder/dataflow.rs b/hugr-core/src/builder/dataflow.rs index 8e13c8158..a50289aec 100644 --- a/hugr-core/src/builder/dataflow.rs +++ b/hugr-core/src/builder/dataflow.rs @@ -7,7 +7,7 @@ use std::marker::PhantomData; use crate::hugr::{HugrView, ValidationError}; use crate::ops; -use crate::types::{FunctionType, TypeScheme}; +use crate::types::{FunctionType, PolyFuncType}; use crate::extension::ExtensionRegistry; use crate::Node; @@ -140,7 +140,7 @@ impl FunctionBuilder { /// Error in adding DFG child nodes. pub fn new( name: impl Into, - signature: impl Into, + signature: impl Into, ) -> Result { let signature = signature.into(); let body = signature.body().clone(); @@ -527,7 +527,7 @@ pub(crate) mod test { // Can *declare* a function that takes a function-value of unknown #args FunctionBuilder::new( "bad_eval", - TypeScheme::new( + PolyFuncType::new( [TypeParam::new_list(TypeBound::Copyable)], FunctionType::new( Type::new_function(FunctionTypeRV::new(USIZE_T, tv.clone())), diff --git a/hugr-core/src/builder/module.rs b/hugr-core/src/builder/module.rs index d5f25dd42..a57acc76b 100644 --- a/hugr-core/src/builder/module.rs +++ b/hugr-core/src/builder/module.rs @@ -9,7 +9,7 @@ use crate::hugr::internal::HugrMutInternals; use crate::hugr::views::HugrView; use crate::hugr::ValidationError; use crate::ops; -use crate::types::{Type, TypeBound, TypeScheme}; +use crate::types::{PolyFuncType, Type, TypeBound}; use crate::ops::handle::{AliasID, FuncID, NodeHandle}; @@ -100,7 +100,7 @@ impl + AsRef> ModuleBuilder { pub fn declare( &mut self, name: impl Into, - signature: TypeScheme, + signature: PolyFuncType, ) -> Result, BuildError> { // TODO add param names to metadata let declare_n = self.add_child_node(ops::FuncDecl { diff --git a/hugr-core/src/extension/declarative/signature.rs b/hugr-core/src/extension/declarative/signature.rs index 896ed7077..59c44e07b 100644 --- a/hugr-core/src/extension/declarative/signature.rs +++ b/hugr-core/src/extension/declarative/signature.rs @@ -14,7 +14,7 @@ use smol_str::SmolStr; use crate::extension::prelude::PRELUDE_ID; use crate::extension::{ExtensionSet, SignatureFunc, TypeDef}; use crate::types::type_param::TypeParam; -use crate::types::{CustomType, FunctionTypeRV, Type, TypeRowRV, TypeSchemeRV}; +use crate::types::{CustomType, FunctionTypeRV, PolyFuncTypeRV, Type, TypeRowRV}; use crate::Extension; use super::{DeclarationContext, ExtensionDeclarationError}; @@ -56,7 +56,7 @@ impl SignatureDeclaration { extension_reqs: self.extensions.clone(), }; - let poly_func = TypeSchemeRV::new(op_params, body); + let poly_func = PolyFuncTypeRV::new(op_params, body); Ok(poly_func.into()) } } diff --git a/hugr-core/src/extension/op_def.rs b/hugr-core/src/extension/op_def.rs index f158c9bca..816e43fb0 100644 --- a/hugr-core/src/extension/op_def.rs +++ b/hugr-core/src/extension/op_def.rs @@ -11,7 +11,7 @@ use super::{ use crate::ops::{OpName, OpNameRef}; use crate::types::type_param::{check_type_args, TypeArg, TypeParam}; -use crate::types::{FunctionType, FunctionTypeRV, TypeSchemeRV}; +use crate::types::{FunctionType, FunctionTypeRV, PolyFuncTypeRV}; use crate::Hugr; /// Trait necessary for binary computations of OpDef signature @@ -24,7 +24,7 @@ pub trait CustomSignatureFunc: Send + Sync { arg_values: &[TypeArg], def: &'o OpDef, extension_registry: &ExtensionRegistry, - ) -> Result; + ) -> Result; /// The declared type parameters which require values in order for signature to /// be computed. fn static_params(&self) -> &[TypeParam]; @@ -34,7 +34,7 @@ pub trait CustomSignatureFunc: Send + Sync { pub trait SignatureFromArgs: Send + Sync { /// Compute signature of node given /// values for the type parameters. - fn compute_signature(&self, arg_values: &[TypeArg]) -> Result; + fn compute_signature(&self, arg_values: &[TypeArg]) -> Result; /// The declared type parameters which require values in order for signature to /// be computed. fn static_params(&self) -> &[TypeParam]; @@ -47,7 +47,7 @@ impl CustomSignatureFunc for T { arg_values: &[TypeArg], _def: &'o OpDef, _extension_registry: &ExtensionRegistry, - ) -> Result { + ) -> Result { SignatureFromArgs::compute_signature(self, arg_values) } @@ -57,7 +57,7 @@ impl CustomSignatureFunc for T { } } -/// Trait for validating type arguments to a TypeSchemeRV beyond conformation to +/// Trait for validating type arguments to a PolyFuncTypeRV beyond conformation to /// declared type parameter (which should have been checked beforehand). pub trait ValidateTypeArgs: Send + Sync { /// Validate the type arguments of node given @@ -71,7 +71,7 @@ pub trait ValidateTypeArgs: Send + Sync { ) -> Result<(), SignatureError>; } -/// Trait for validating type arguments to a TypeSchemeRV beyond conformation to +/// Trait for validating type arguments to a PolyFuncTypeRV beyond conformation to /// declared type parameter (which should have been checked beforehand), given just the arguments. pub trait ValidateJustArgs: Send + Sync { /// Validate the type arguments of node given @@ -114,30 +114,30 @@ pub trait CustomLowerFunc: Send + Sync { ) -> Option; } -/// Encode a signature as `TypeSchemeRV` but optionally allow validating type +/// Encode a signature as `PolyFuncTypeRV` but optionally allow validating type /// arguments via a custom binary. The binary cannot be serialized so will be /// lost over a serialization round-trip. #[derive(serde::Deserialize, serde::Serialize)] pub struct CustomValidator { #[serde(flatten)] - poly_func: TypeSchemeRV, + poly_func: PolyFuncTypeRV, #[serde(skip)] pub(crate) validate: Box, } impl CustomValidator { - /// Encode a signature using a `TypeSchemeRV` - pub fn from_polyfunc(poly_func: impl Into) -> Self { + /// Encode a signature using a `PolyFuncTypeRV` + pub fn from_polyfunc(poly_func: impl Into) -> Self { Self { poly_func: poly_func.into(), validate: Default::default(), } } - /// Encode a signature using a `TypeSchemeRV`, with a custom function for + /// Encode a signature using a `PolyFuncTypeRV`, with a custom function for /// validating type arguments before returning the signature. pub fn new_with_validator( - poly_func: impl Into, + poly_func: impl Into, validate: impl ValidateTypeArgs + 'static, ) -> Self { Self { @@ -153,10 +153,10 @@ pub enum SignatureFunc { // Note: except for serialization, we could have type schemes just implement the same // CustomSignatureFunc trait too, and replace this enum with Box. // However instead we treat all CustomFunc's as non-serializable. - /// A TypeScheme (polymorphic function type), with optional custom + /// A PolyFuncType (polymorphic function type), with optional custom /// validation for provided type arguments, #[serde(rename = "signature")] - TypeScheme(CustomValidator), + PolyFuncType(CustomValidator), #[serde(skip)] /// A custom binary which computes a polymorphic function type given values /// for its static type parameters. @@ -186,34 +186,34 @@ impl From for SignatureFunc { } } -impl From for SignatureFunc { - fn from(v: TypeSchemeRV) -> Self { - Self::TypeScheme(CustomValidator::from_polyfunc(v)) +impl From for SignatureFunc { + fn from(v: PolyFuncTypeRV) -> Self { + Self::PolyFuncType(CustomValidator::from_polyfunc(v)) } } impl From for SignatureFunc { fn from(v: FunctionTypeRV) -> Self { - Self::TypeScheme(CustomValidator::from_polyfunc(v)) + Self::PolyFuncType(CustomValidator::from_polyfunc(v)) } } impl From for SignatureFunc { fn from(v: FunctionType) -> Self { - Self::TypeScheme(CustomValidator::from_polyfunc(FunctionTypeRV::from(v))) + Self::PolyFuncType(CustomValidator::from_polyfunc(FunctionTypeRV::from(v))) } } impl From for SignatureFunc { fn from(v: CustomValidator) -> Self { - Self::TypeScheme(v) + Self::PolyFuncType(v) } } impl SignatureFunc { fn static_params(&self) -> &[TypeParam] { match self { - SignatureFunc::TypeScheme(ts) => ts.poly_func.params(), + SignatureFunc::PolyFuncType(ts) => ts.poly_func.params(), SignatureFunc::CustomFunc(func) => func.static_params(), } } @@ -235,9 +235,9 @@ impl SignatureFunc { args: &[TypeArg], exts: &ExtensionRegistry, ) -> Result { - let temp: TypeSchemeRV; // to keep alive + let temp: PolyFuncTypeRV; // to keep alive let (pf, args) = match &self { - SignatureFunc::TypeScheme(custom) => { + SignatureFunc::PolyFuncType(custom) => { custom.validate.validate(args, def, exts)?; (&custom.poly_func, args) } @@ -264,7 +264,7 @@ impl SignatureFunc { impl Debug for SignatureFunc { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - Self::TypeScheme(ts) => ts.poly_func.fmt(f), + Self::PolyFuncType(ts) => ts.poly_func.fmt(f), Self::CustomFunc { .. } => f.write_str(""), } } @@ -338,9 +338,9 @@ impl OpDef { exts: &ExtensionRegistry, var_decls: &[TypeParam], ) -> Result<(), SignatureError> { - let temp: TypeSchemeRV; // to keep alive + let temp: PolyFuncTypeRV; // to keep alive let (pf, args) = match &self.signature_func { - SignatureFunc::TypeScheme(ts) => (&ts.poly_func, args), + SignatureFunc::PolyFuncType(ts) => (&ts.poly_func, args), SignatureFunc::CustomFunc(custom) => { let (static_args, other_args) = args.split_at(min(custom.static_params().len(), args.len())); @@ -412,7 +412,7 @@ impl OpDef { pub(super) fn validate(&self, exts: &ExtensionRegistry) -> Result<(), SignatureError> { // TODO https://github.com/CQCL/hugr/issues/624 validate declared TypeParams // for both type scheme and custom binary - if let SignatureFunc::TypeScheme(ts) = &self.signature_func { + if let SignatureFunc::PolyFuncType(ts) = &self.signature_func { // The type scheme may contain row variables so be of variable length; // these will have to be substituted to fixed-length concrete types when // the OpDef is instantiated into an actual OpType. @@ -454,7 +454,7 @@ impl OpDef { impl Extension { /// Add an operation definition to the extension. Must be a type scheme - /// (defined by a [`TypeSchemeRV`]), a type scheme along with binary + /// (defined by a [`PolyFuncTypeRV`]), a type scheme along with binary /// validation for type arguments ([`CustomValidator`]), or a custom binary /// function for computing the signature given type arguments (`impl [CustomSignatureFunc]`). pub fn add_op( @@ -496,7 +496,7 @@ pub(super) mod test { use crate::ops::{CustomOp, OpName}; use crate::std_extensions::collections::{EXTENSION, LIST_TYPENAME}; use crate::types::type_param::{TypeArgError, TypeParam}; - use crate::types::{FunctionType, Type, TypeArg, TypeBound, TypeRV, TypeSchemeRV}; + use crate::types::{FunctionType, PolyFuncTypeRV, Type, TypeArg, TypeBound, TypeRV}; use crate::{const_extension_ids, Extension}; const_extension_ids! { @@ -511,7 +511,7 @@ pub(super) mod test { assert!(op_def.constant_folder.is_none()); assert!(matches!( op_def.signature_func, - SignatureFunc::TypeScheme(_) + SignatureFunc::PolyFuncType(_) )); assert!(op_def .lower_funcs @@ -553,7 +553,7 @@ pub(super) mod test { // a compile error here. To fix: modify the fields matched on here, // maintaining the lack of `..` and, for each part that is // serializable, ensure we are checking it for equality below. - SignatureFunc::TypeScheme(CustomValidator { + SignatureFunc::PolyFuncType(CustomValidator { poly_func, validate: _, }) => Some(poly_func.clone()), @@ -592,7 +592,7 @@ pub(super) mod test { let list_of_var = Type::new_extension(list_def.instantiate(vec![TypeArg::new_var_use(0, TP)])?); const OP_NAME: OpName = OpName::new_inline("Reverse"); - let type_scheme = TypeSchemeRV::new(vec![TP], FunctionType::new_endo(vec![list_of_var])); + let type_scheme = PolyFuncTypeRV::new(vec![TP], FunctionType::new_endo(vec![list_of_var])); let def = e.add_op(OP_NAME, "desc".into(), type_scheme)?; def.add_lower_func(LowerFunc::FixedHugr { @@ -625,7 +625,7 @@ pub(super) mod test { #[test] fn binary_polyfunc() -> Result<(), Box> { - // Test a custom binary `compute_signature` that returns a TypeSchemeRV + // Test a custom binary `compute_signature` that returns a PolyFuncTypeRV // where the latter declares more type params itself. In particular, // we should be able to substitute (external) type variables into the latter, // but not pass them into the former (custom binary function). @@ -634,7 +634,7 @@ pub(super) mod test { fn compute_signature( &self, arg_values: &[TypeArg], - ) -> Result { + ) -> Result { const TP: TypeParam = TypeParam::Type { b: TypeBound::Any }; let [TypeArg::BoundedNat { n }] = arg_values else { return Err(SignatureError::InvalidTypeArgs); @@ -643,7 +643,7 @@ pub(super) mod test { let tvs: Vec = (0..n) .map(|_| Type::new_var_use(0, TypeBound::Any)) .collect(); - Ok(TypeSchemeRV::new( + Ok(PolyFuncTypeRV::new( vec![TP.to_owned()], FunctionType::new(tvs.clone(), vec![Type::new_tuple(tvs)]), )) @@ -714,13 +714,13 @@ pub(super) mod test { #[test] fn type_scheme_instantiate_var() -> Result<(), Box> { - // Check that we can instantiate a TypeSchemeRV-scheme with an (external) + // Check that we can instantiate a PolyFuncTypeRV-scheme with an (external) // type variable let mut e = Extension::new(EXT_ID); let def = e.add_op( "SimpleOp".into(), "".into(), - TypeSchemeRV::new( + PolyFuncTypeRV::new( vec![TypeBound::Any.into()], FunctionType::new_endo(vec![Type::new_var_use(0, TypeBound::Any)]), ), @@ -760,7 +760,7 @@ pub(super) mod test { let def = e.add_op( "SimpleOp".into(), "".into(), - TypeSchemeRV::new(params.clone(), fun_ty), + PolyFuncTypeRV::new(params.clone(), fun_ty), )?; // Concrete extension set @@ -786,7 +786,7 @@ pub(super) mod test { extension::{ op_def::LowerFunc, CustomValidator, ExtensionId, ExtensionSet, OpDef, SignatureFunc, }, - types::TypeSchemeRV, + types::PolyFuncTypeRV, }; impl Arbitrary for SignatureFunc { @@ -796,8 +796,8 @@ pub(super) mod test { // TODO there is also SignatureFunc::CustomFunc, but for now // this is not serialized. When it is, we should generate // examples here . - any::() - .prop_map(|x| SignatureFunc::TypeScheme(CustomValidator::from_polyfunc(x))) + any::() + .prop_map(|x| SignatureFunc::PolyFuncType(CustomValidator::from_polyfunc(x))) .boxed() } } diff --git a/hugr-core/src/extension/prelude.rs b/hugr-core/src/extension/prelude.rs index c82a7a8be..55a2033e6 100644 --- a/hugr-core/src/extension/prelude.rs +++ b/hugr-core/src/extension/prelude.rs @@ -11,7 +11,7 @@ use crate::{ type_row, types::{ type_param::{TypeArg, TypeParam}, - CustomType, FunctionType, Type, TypeBound, TypeSchemeRV, + CustomType, FunctionType, PolyFuncTypeRV, Type, TypeBound, }, Extension, }; @@ -21,7 +21,7 @@ struct ArrayOpCustom; const MAX: &[TypeParam; 1] = &[TypeParam::max_nat()]; impl SignatureFromArgs for ArrayOpCustom { - fn compute_signature(&self, arg_values: &[TypeArg]) -> Result { + fn compute_signature(&self, arg_values: &[TypeArg]) -> Result { let [TypeArg::BoundedNat { n }] = *arg_values else { return Err(SignatureError::InvalidTypeArgs); }; @@ -30,7 +30,7 @@ impl SignatureFromArgs for ArrayOpCustom { let var_arg_row = vec![elem_ty_var.clone(); n as usize]; let other_row = vec![array_type(TypeArg::BoundedNat { n }, elem_ty_var.clone())]; - Ok(TypeSchemeRV::new( + Ok(PolyFuncTypeRV::new( vec![TypeBound::Any.into()], FunctionTypeRV::new(var_arg_row, other_row), )) @@ -43,7 +43,7 @@ impl SignatureFromArgs for ArrayOpCustom { struct GenericOpCustom; impl SignatureFromArgs for GenericOpCustom { - fn compute_signature(&self, arg_values: &[TypeArg]) -> Result { + fn compute_signature(&self, arg_values: &[TypeArg]) -> Result { let [arg0, arg1] = arg_values else { return Err(SignatureError::InvalidTypeArgs); }; diff --git a/hugr-core/src/hugr/serialize/test.rs b/hugr-core/src/hugr/serialize/test.rs index 61ffa28b4..d24e9d8e6 100644 --- a/hugr-core/src/hugr/serialize/test.rs +++ b/hugr-core/src/hugr/serialize/test.rs @@ -15,8 +15,8 @@ use crate::std_extensions::arithmetic::int_types::{int_custom_type, ConstInt, IN use crate::std_extensions::logic::NotOp; use crate::types::type_param::TypeParam; use crate::types::{ - FunctionType, FunctionTypeRV, SumType, Type, TypeArg, TypeBound, TypeRV, TypeScheme, - TypeSchemeRV, + FunctionType, FunctionTypeRV, PolyFuncType, PolyFuncTypeRV, SumType, Type, TypeArg, TypeBound, + TypeRV, }; use crate::{type_row, OutgoingPort}; @@ -35,7 +35,7 @@ const QB: Type = crate::extension::prelude::QB_T; struct SerTestingV1 { typ: Option, sum_type: Option, - poly_func_type: Option, + poly_func_type: Option, value: Option, optype: Option, op_def: Option, @@ -90,14 +90,14 @@ macro_rules! impl_sertesting_from { impl_sertesting_from!(crate::types::TypeRV, typ); impl_sertesting_from!(crate::types::SumType, sum_type); -impl_sertesting_from!(crate::types::TypeSchemeRV, poly_func_type); +impl_sertesting_from!(crate::types::PolyFuncTypeRV, poly_func_type); impl_sertesting_from!(crate::ops::Value, value); impl_sertesting_from!(NodeSer, optype); impl_sertesting_from!(SimpleOpDef, op_def); -impl From for TestingModel { - fn from(v: TypeScheme) -> Self { - let v: TypeSchemeRV = v.into(); +impl From for TestingModel { + fn from(v: PolyFuncType) -> Self { + let v: PolyFuncTypeRV = v.into(); v.into() } } @@ -428,14 +428,14 @@ fn roundtrip_value(#[case] value: Value) { check_testing_roundtrip(value); } -fn polyfunctype1() -> TypeScheme { +fn polyfunctype1() -> PolyFuncType { let mut extension_set = ExtensionSet::new(); extension_set.insert_type_var(1); let function_type = FunctionType::new_endo(type_row![]).with_extension_delta(extension_set); - TypeScheme::new([TypeParam::max_nat(), TypeParam::Extensions], function_type) + PolyFuncType::new([TypeParam::max_nat(), TypeParam::Extensions], function_type) } -fn polyfunctype2() -> TypeSchemeRV { +fn polyfunctype2() -> PolyFuncTypeRV { let tv0 = TypeRV::new_row_var_use(0, TypeBound::Any); let tv1 = TypeRV::new_row_var_use(1, TypeBound::Eq); let params = [TypeBound::Any, TypeBound::Eq].map(TypeParam::new_list); @@ -443,7 +443,7 @@ fn polyfunctype2() -> TypeSchemeRV { TypeRV::new_function(FunctionTypeRV::new(tv0.clone(), tv1.clone())), tv0, ]; - let res = TypeSchemeRV::new(params, FunctionTypeRV::new(inputs, tv1)); + let res = PolyFuncTypeRV::new(params, FunctionTypeRV::new(inputs, tv1)); // Just check we've got the arguments the right way round // (not that it really matters for the serialization schema we have) res.validate(&EMPTY_REG).unwrap(); @@ -453,28 +453,28 @@ fn polyfunctype2() -> TypeSchemeRV { #[rstest] #[case(FunctionType::new_endo(type_row![]).into())] #[case(polyfunctype1())] -#[case(TypeScheme::new([TypeParam::Opaque { ty: int_custom_type(TypeArg::BoundedNat { n: 1 }) }], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Copyable)])))] -#[case(TypeScheme::new([TypeBound::Eq.into()], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Eq)])))] -#[case(TypeScheme::new([TypeParam::new_list(TypeBound::Any)], FunctionType::new_endo(type_row![])))] -#[case(TypeScheme::new([TypeParam::Tuple { params: [TypeBound::Any.into(), TypeParam::bounded_nat(2.try_into().unwrap())].into() }], FunctionType::new_endo(type_row![])))] -#[case(TypeScheme::new( +#[case(PolyFuncType::new([TypeParam::Opaque { ty: int_custom_type(TypeArg::BoundedNat { n: 1 }) }], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Copyable)])))] +#[case(PolyFuncType::new([TypeBound::Eq.into()], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Eq)])))] +#[case(PolyFuncType::new([TypeParam::new_list(TypeBound::Any)], FunctionType::new_endo(type_row![])))] +#[case(PolyFuncType::new([TypeParam::Tuple { params: [TypeBound::Any.into(), TypeParam::bounded_nat(2.try_into().unwrap())].into() }], FunctionType::new_endo(type_row![])))] +#[case(PolyFuncType::new( [TypeParam::new_list(TypeBound::Any)], FunctionType::new_endo(Type::new_tuple(TypeRV::new_row_var_use(0, TypeBound::Any)))))] -fn roundtrip_polyfunctype_fixedlen(#[case] poly_func_type: TypeScheme) { +fn roundtrip_polyfunctype_fixedlen(#[case] poly_func_type: PolyFuncType) { check_testing_roundtrip(poly_func_type) } #[rstest] #[case(FunctionTypeRV::new_endo(type_row![]).into())] -#[case(TypeSchemeRV::new([TypeParam::Opaque { ty: int_custom_type(TypeArg::BoundedNat { n: 1 }) }], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Copyable)])))] -#[case(TypeSchemeRV::new([TypeBound::Eq.into()], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Eq)])))] -#[case(TypeSchemeRV::new([TypeParam::new_list(TypeBound::Any)], FunctionType::new_endo(type_row![])))] -#[case(TypeSchemeRV::new([TypeParam::Tuple { params: [TypeBound::Any.into(), TypeParam::bounded_nat(2.try_into().unwrap())].into() }], FunctionType::new_endo(type_row![])))] -#[case(TypeSchemeRV::new( +#[case(PolyFuncTypeRV::new([TypeParam::Opaque { ty: int_custom_type(TypeArg::BoundedNat { n: 1 }) }], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Copyable)])))] +#[case(PolyFuncTypeRV::new([TypeBound::Eq.into()], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Eq)])))] +#[case(PolyFuncTypeRV::new([TypeParam::new_list(TypeBound::Any)], FunctionType::new_endo(type_row![])))] +#[case(PolyFuncTypeRV::new([TypeParam::Tuple { params: [TypeBound::Any.into(), TypeParam::bounded_nat(2.try_into().unwrap())].into() }], FunctionType::new_endo(type_row![])))] +#[case(PolyFuncTypeRV::new( [TypeParam::new_list(TypeBound::Any)], FunctionTypeRV::new_endo(TypeRV::new_row_var_use(0, TypeBound::Any))))] #[case(polyfunctype2())] -fn roundtrip_polyfunctype_varlen(#[case] poly_func_type: TypeSchemeRV) { +fn roundtrip_polyfunctype_varlen(#[case] poly_func_type: PolyFuncTypeRV) { check_testing_roundtrip(poly_func_type) } @@ -512,7 +512,7 @@ mod proptest { use super::check_testing_roundtrip; use super::{NodeSer, SimpleOpDef}; use crate::ops::{OpType, Value}; - use crate::types::{Type, TypeSchemeRV}; + use crate::types::{PolyFuncTypeRV, Type}; use proptest::prelude::*; impl Arbitrary for NodeSer { @@ -535,7 +535,7 @@ mod proptest { } #[test] - fn prop_roundtrip_poly_func_type(t: TypeSchemeRV) { + fn prop_roundtrip_poly_func_type(t: PolyFuncTypeRV) { check_testing_roundtrip(t) } diff --git a/hugr-core/src/hugr/validate/test.rs b/hugr-core/src/hugr/validate/test.rs index 089d368a1..50390cfb3 100644 --- a/hugr-core/src/hugr/validate/test.rs +++ b/hugr-core/src/hugr/validate/test.rs @@ -21,8 +21,8 @@ use crate::std_extensions::logic::test::{and_op, or_op}; use crate::std_extensions::logic::{self, NotOp}; use crate::types::type_param::{TypeArg, TypeArgError}; use crate::types::{ - CustomType, FunctionType, FunctionTypeRV, Type, TypeBound, TypeRV, TypeRow, TypeScheme, - TypeSchemeRV, + CustomType, FunctionType, FunctionTypeRV, PolyFuncType, PolyFuncTypeRV, Type, TypeBound, + TypeRV, TypeRow, }; use crate::{const_extension_ids, test_file, type_row, Direction, IncomingPort, Node}; @@ -464,7 +464,7 @@ fn typevars_declared() -> Result<(), Box> { // Base case let f = FunctionBuilder::new( "myfunc", - TypeScheme::new( + PolyFuncType::new( [TypeBound::Any.into()], FunctionType::new_endo(vec![Type::new_var_use(0, TypeBound::Any)]), ), @@ -474,7 +474,7 @@ fn typevars_declared() -> Result<(), Box> { // Type refers to undeclared variable let f = FunctionBuilder::new( "myfunc", - TypeScheme::new( + PolyFuncType::new( [TypeBound::Any.into()], FunctionType::new_endo(vec![Type::new_var_use(1, TypeBound::Any)]), ), @@ -484,7 +484,7 @@ fn typevars_declared() -> Result<(), Box> { // Variable declaration incorrectly copied to use site let f = FunctionBuilder::new( "myfunc", - TypeScheme::new( + PolyFuncType::new( [TypeBound::Any.into()], FunctionType::new_endo(vec![Type::new_var_use(1, TypeBound::Copyable)]), ), @@ -502,14 +502,14 @@ fn nested_typevars() -> Result<(), Box> { fn build(t: Type) -> Result { let mut outer = FunctionBuilder::new( "outer", - TypeScheme::new( + PolyFuncType::new( [OUTER_BOUND.into()], FunctionType::new_endo(vec![Type::new_var_use(0, TypeBound::Any)]), ), )?; let inner = outer.define_function( "inner", - TypeScheme::new([INNER_BOUND.into()], FunctionType::new_endo(vec![t])), + PolyFuncType::new([INNER_BOUND.into()], FunctionType::new_endo(vec![t])), )?; let [w] = inner.input_wires_arr(); inner.finish_with_outputs([w])?; @@ -548,7 +548,7 @@ fn no_polymorphic_consts() -> Result<(), Box> { let reg = ExtensionRegistry::try_new([collections::EXTENSION.to_owned()]).unwrap(); let mut def = FunctionBuilder::new( "myfunc", - TypeScheme::new( + PolyFuncType::new( [BOUND], FunctionType::new(vec![], vec![list_of_var.clone()]) .with_extension_delta(collections::EXTENSION_NAME), @@ -580,14 +580,14 @@ pub(crate) fn extension_with_eval_parallel() -> Extension { let inputs = TypeRV::new_row_var_use(0, TypeBound::Any); let outputs = TypeRV::new_row_var_use(1, TypeBound::Any); let evaled_fn = TypeRV::new_function(FunctionTypeRV::new(inputs.clone(), outputs.clone())); - let pf = TypeSchemeRV::new( + let pf = PolyFuncTypeRV::new( [rowp.clone(), rowp.clone()], FunctionTypeRV::new(vec![evaled_fn, inputs], outputs), ); e.add_op("eval".into(), "".into(), pf).unwrap(); let rv = |idx| TypeRV::new_row_var_use(idx, TypeBound::Any); - let pf = TypeSchemeRV::new( + let pf = PolyFuncTypeRV::new( [rowp.clone(), rowp.clone(), rowp.clone(), rowp.clone()], FunctionType::new( vec![ @@ -648,7 +648,7 @@ fn row_variables() -> Result<(), Box> { let ft_usz = Type::new_function(FunctionTypeRV::new_endo(vec![tv.clone(), USIZE_T.into()])); let mut fb = FunctionBuilder::new( "id", - TypeScheme::new( + PolyFuncType::new( [TypeParam::new_list(TypeBound::Any)], FunctionType::new(inner_ft.clone(), ft_usz), ), @@ -701,7 +701,7 @@ fn test_polymorphic_call() -> Result<(), Box> { e.add_op( "eval".into(), "".into(), - TypeSchemeRV::new( + PolyFuncTypeRV::new( params.clone(), FunctionType::new( vec![evaled_fn, Type::new_var_use(0, TypeBound::Any)], @@ -726,7 +726,7 @@ fn test_polymorphic_call() -> Result<(), Box> { let es = ExtensionSet::type_var(0); let mut f = d.define_function( "two_ints", - TypeScheme::new( + PolyFuncType::new( vec![TypeParam::Extensions], FunctionType::new(vec![utou(es.clone()), int_pair.clone()], int_pair.clone()) .with_extension_delta(es.clone()), @@ -782,7 +782,7 @@ fn test_polymorphic_load() -> Result<(), Box> { let mut m = ModuleBuilder::new(); let id = m.declare( "id", - TypeScheme::new( + PolyFuncType::new( vec![TypeBound::Any.into()], FunctionType::new_endo(vec![Type::new_var_use(0, TypeBound::Any)]), ), diff --git a/hugr-core/src/hugr/views.rs b/hugr-core/src/hugr/views.rs index 80efb2616..60950ca3d 100644 --- a/hugr-core/src/hugr/views.rs +++ b/hugr-core/src/hugr/views.rs @@ -32,7 +32,7 @@ use crate::extension::ExtensionRegistry; use crate::ops::handle::NodeHandle; use crate::ops::{OpParent, OpTag, OpTrait, OpType}; -use crate::types::{EdgeKind, FunctionType, Type, TypeScheme}; +use crate::types::{EdgeKind, FunctionType, PolyFuncType, Type}; use crate::{Direction, IncomingPort, Node, OutgoingPort, Port}; use itertools::Either; @@ -347,7 +347,7 @@ pub trait HugrView: HugrInternals { /// of the function. /// /// Otherwise, returns `None`. - fn poly_func_type(&self) -> Option { + fn poly_func_type(&self) -> Option { match self.root_type() { OpType::FuncDecl(decl) => Some(decl.signature.clone()), OpType::FuncDefn(defn) => Some(defn.signature.clone()), diff --git a/hugr-core/src/ops/dataflow.rs b/hugr-core/src/ops/dataflow.rs index 2f9ccfd3e..54202ffc0 100644 --- a/hugr-core/src/ops/dataflow.rs +++ b/hugr-core/src/ops/dataflow.rs @@ -4,7 +4,7 @@ use super::{impl_op_name, OpTag, OpTrait}; use crate::extension::{ExtensionRegistry, ExtensionSet, SignatureError}; use crate::ops::StaticTag; -use crate::types::{EdgeKind, FunctionType, Type, TypeArg, TypeRow, TypeScheme}; +use crate::types::{EdgeKind, FunctionType, PolyFuncType, Type, TypeArg, TypeRow}; use crate::IncomingPort; #[cfg(test)] @@ -159,7 +159,7 @@ impl StaticTag for T { #[cfg_attr(test, derive(Arbitrary))] pub struct Call { /// Signature of function being called - func_sig: TypeScheme, + func_sig: PolyFuncType, type_args: Vec, instantiation: FunctionType, // Cache, so we can fail in try_new() not in signature() } @@ -186,7 +186,7 @@ impl Call { /// /// [TypeParam]: crate::types::type_param::TypeParam pub fn try_new( - func_sig: TypeScheme, + func_sig: PolyFuncType, type_args: impl Into>, exts: &ExtensionRegistry, ) -> Result { @@ -201,7 +201,7 @@ impl Call { #[inline] /// Return the signature of the function called by this op. - pub fn called_function_type(&self) -> &TypeScheme { + pub fn called_function_type(&self) -> &PolyFuncType { &self.func_sig } @@ -329,7 +329,7 @@ impl LoadConstant { #[cfg_attr(test, derive(Arbitrary))] pub struct LoadFunction { /// Signature of the function - func_sig: TypeScheme, + func_sig: PolyFuncType, type_args: Vec, signature: FunctionType, // Cache, so we can fail in try_new() not in signature() } @@ -355,7 +355,7 @@ impl LoadFunction { /// /// [TypeParam]: crate::types::type_param::TypeParam pub fn try_new( - func_sig: TypeScheme, + func_sig: PolyFuncType, type_args: impl Into>, exts: &ExtensionRegistry, ) -> Result { @@ -371,7 +371,7 @@ impl LoadFunction { #[inline] /// Return the type of the function loaded by this op. - pub fn function_type(&self) -> &TypeScheme { + pub fn function_type(&self) -> &PolyFuncType { &self.func_sig } diff --git a/hugr-core/src/ops/module.rs b/hugr-core/src/ops/module.rs index ac4fa596d..ea4e67744 100644 --- a/hugr-core/src/ops/module.rs +++ b/hugr-core/src/ops/module.rs @@ -7,7 +7,7 @@ use { ::proptest_derive::Arbitrary, }; -use crate::types::{EdgeKind, FunctionType, TypeScheme}; +use crate::types::{EdgeKind, FunctionType, PolyFuncType}; use crate::types::{Type, TypeBound}; use super::dataflow::DataflowParent; @@ -55,7 +55,7 @@ pub struct FuncDefn { #[cfg_attr(test, proptest(strategy = "any_nonempty_string()"))] pub name: String, /// Signature of the function - pub signature: TypeScheme, + pub signature: PolyFuncType, } impl_op_name!(FuncDefn); @@ -91,7 +91,7 @@ pub struct FuncDecl { #[cfg_attr(test, proptest(strategy = "any_nonempty_string()"))] pub name: String, /// Signature of the function - pub signature: TypeScheme, + pub signature: PolyFuncType, } impl_op_name!(FuncDecl); diff --git a/hugr-core/src/std_extensions/arithmetic/conversions.rs b/hugr-core/src/std_extensions/arithmetic/conversions.rs index 138a8caba..924604f26 100644 --- a/hugr-core/src/std_extensions/arithmetic/conversions.rs +++ b/hugr-core/src/std_extensions/arithmetic/conversions.rs @@ -12,7 +12,7 @@ use crate::{ }, ops::{custom::ExtensionOp, NamedOp}, type_row, - types::{FunctionTypeRV, TypeArg, TypeRV, TypeSchemeRV}, + types::{FunctionTypeRV, PolyFuncTypeRV, TypeArg, TypeRV}, Extension, }; @@ -45,7 +45,7 @@ impl MakeOpDef for ConvertOpDef { fn signature(&self) -> SignatureFunc { use ConvertOpDef::*; - TypeSchemeRV::new( + PolyFuncTypeRV::new( vec![LOG_WIDTH_TYPE_PARAM], match self { trunc_s | trunc_u => FunctionTypeRV::new( diff --git a/hugr-core/src/std_extensions/arithmetic/int_ops.rs b/hugr-core/src/std_extensions/arithmetic/int_ops.rs index bc81636da..f15db409c 100644 --- a/hugr-core/src/std_extensions/arithmetic/int_ops.rs +++ b/hugr-core/src/std_extensions/arithmetic/int_ops.rs @@ -10,7 +10,7 @@ use crate::ops::custom::ExtensionOp; use crate::ops::{NamedOp, OpName}; use crate::std_extensions::arithmetic::int_types::int_type; use crate::type_row; -use crate::types::{FunctionTypeRV, TypeRowRV, TypeSchemeRV}; +use crate::types::{FunctionTypeRV, PolyFuncTypeRV, TypeRowRV}; use crate::utils::collect_array; use crate::{ @@ -160,7 +160,7 @@ impl MakeOpDef for IntOpDef { ishl | ishr | irotl | irotr => { int_polytype(2, vec![int_tv(0), int_tv(1)], vec![int_tv(0)]).into() } - itostring_u | itostring_s => TypeSchemeRV::new( + itostring_u | itostring_s => PolyFuncTypeRV::new( vec![LOG_WIDTH_TYPE_PARAM], FunctionTypeRV::new(vec![int_tv(0)], vec![STRING_TYPE]), ) @@ -238,20 +238,20 @@ fn int_polytype( n_vars: usize, input: impl Into, output: impl Into, -) -> TypeSchemeRV { - TypeSchemeRV::new( +) -> PolyFuncTypeRV { + PolyFuncTypeRV::new( vec![LOG_WIDTH_TYPE_PARAM; n_vars], FunctionTypeRV::new(input, output), ) } -fn ibinop_sig() -> TypeSchemeRV { +fn ibinop_sig() -> PolyFuncTypeRV { let int_type_var = int_tv(0); int_polytype(1, vec![int_type_var.clone(); 2], vec![int_type_var]) } -fn iunop_sig() -> TypeSchemeRV { +fn iunop_sig() -> PolyFuncTypeRV { let int_type_var = int_tv(0); int_polytype(1, vec![int_type_var.clone()], vec![int_type_var]) } diff --git a/hugr-core/src/std_extensions/collections.rs b/hugr-core/src/std_extensions/collections.rs index f1a4f8319..315331fdb 100644 --- a/hugr-core/src/std_extensions/collections.rs +++ b/hugr-core/src/std_extensions/collections.rs @@ -17,7 +17,7 @@ use crate::{ ops::{self, custom::ExtensionOp, NamedOp}, types::{ type_param::{TypeArg, TypeParam}, - CustomCheckFailure, CustomType, FunctionTypeRV, Type, TypeBound, TypeSchemeRV, + CustomCheckFailure, CustomType, FunctionTypeRV, PolyFuncTypeRV, Type, TypeBound, }, utils::sorted_consts, Extension, @@ -155,7 +155,7 @@ fn extension() -> Extension { .add_op( POP_NAME, "Pop from back of list".into(), - TypeSchemeRV::new( + PolyFuncTypeRV::new( vec![TP], FunctionTypeRV::new(vec![l.clone()], vec![l.clone(), e.clone()]), ), @@ -166,7 +166,7 @@ fn extension() -> Extension { .add_op( PUSH_NAME, "Push to back of list".into(), - TypeSchemeRV::new(vec![TP], FunctionTypeRV::new(vec![l.clone(), e], vec![l])), + PolyFuncTypeRV::new(vec![TP], FunctionTypeRV::new(vec![l.clone(), e], vec![l])), ) .unwrap() .set_constant_folder(PushFold); diff --git a/hugr-core/src/std_extensions/logic.rs b/hugr-core/src/std_extensions/logic.rs index 3c8b902e5..231cfd455 100644 --- a/hugr-core/src/std_extensions/logic.rs +++ b/hugr-core/src/std_extensions/logic.rs @@ -162,7 +162,7 @@ fn logic_op_sig() -> impl SignatureFromArgs { fn compute_signature( &self, arg_values: &[TypeArg], - ) -> Result { + ) -> Result { // get the number of input booleans. let [TypeArg::BoundedNat { n }] = *arg_values else { return Err(SignatureError::InvalidTypeArgs); diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index 945b9f693..13625eb7d 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -16,7 +16,7 @@ use crate::types::type_param::check_type_arg; use crate::utils::display_list_with_separator; pub use check::SumTypeError; pub use custom::CustomType; -pub use poly_func::{TypeScheme, TypeSchemeRV}; +pub use poly_func::{PolyFuncType, PolyFuncTypeRV}; pub use signature::{FunctionType, FunctionTypeRV}; use smol_str::SmolStr; pub use type_param::TypeArg; @@ -54,7 +54,7 @@ pub enum EdgeKind { /// /// [FuncDecl]: crate::ops::FuncDecl /// [FuncDefn]: crate::ops::FuncDefn - Function(TypeScheme), + Function(PolyFuncType), /// Explicitly enforce an ordering between nodes in a DDG. StateOrder, } diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index cc9774d15..16cf8e346 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -28,7 +28,7 @@ use super::{signature::FuncTypeBase, MaybeRV, NoRV, RowVariable}; "params.iter().map(ToString::to_string).join(\" \")", "body" )] -pub struct TypeSchemeBase { +pub struct PolyFuncTypeBase { /// The declared type parameters, i.e., these must be instantiated with /// the same number of [TypeArg]s before the function can be called. This /// defines the indices used by variables inside the body. @@ -45,16 +45,16 @@ pub struct TypeSchemeBase { /// [Call]: crate::ops::Call /// [FuncDefn]: crate::ops::FuncDefn /// [FuncDecl]: crate::ops::FuncDecl -pub type TypeScheme = TypeSchemeBase; +pub type PolyFuncType = PolyFuncTypeBase; /// The polymorphic type of an [OpDef], whose number of input and outputs /// may vary according to how [RowVariable]s therein are instantiated. /// /// [OpDef]: crate::extension::OpDef -pub type TypeSchemeRV = TypeSchemeBase; +pub type PolyFuncTypeRV = PolyFuncTypeBase; // deriving Default leads to an impl that only applies for RV: Default -impl Default for TypeSchemeBase { +impl Default for PolyFuncTypeBase { fn default() -> Self { Self { params: Default::default(), @@ -63,7 +63,7 @@ impl Default for TypeSchemeBase { } } -impl From> for TypeSchemeBase { +impl From> for PolyFuncTypeBase { fn from(body: FuncTypeBase) -> Self { Self { params: vec![], @@ -72,8 +72,8 @@ impl From> for TypeSchemeBase { } } -impl From for TypeSchemeRV { - fn from(value: TypeScheme) -> Self { +impl From for PolyFuncTypeRV { + fn from(value: PolyFuncType) -> Self { Self { params: value.params, body: value.body.into(), @@ -81,11 +81,11 @@ impl From for TypeSchemeRV { } } -impl TryFrom> for FuncTypeBase { - /// If the TypeSchemeBase is not monomorphic, fail with its binders +impl TryFrom> for FuncTypeBase { + /// If the PolyFuncTypeBase is not monomorphic, fail with its binders type Error = Vec; - fn try_from(value: TypeSchemeBase) -> Result { + fn try_from(value: PolyFuncTypeBase) -> Result { if value.params.is_empty() { Ok(value.body) } else { @@ -94,7 +94,7 @@ impl TryFrom> for FuncTypeBase { } } -impl TypeSchemeBase { +impl PolyFuncTypeBase { /// The type parameters, aka binders, over which this type is polymorphic pub fn params(&self) -> &[TypeParam] { &self.params @@ -105,7 +105,7 @@ impl TypeSchemeBase { &self.body } - /// Create a new TypeSchemeBase given the kinds of the variables it declares + /// Create a new PolyFuncTypeBase given the kinds of the variables it declares /// and the underlying [FuncTypeBase]. pub fn new(params: impl Into>, body: impl Into>) -> Self { Self { @@ -114,7 +114,7 @@ impl TypeSchemeBase { } } - /// Instantiates an outer [TypeSchemeBase], i.e. with no free variables + /// Instantiates an outer [PolyFuncTypeBase], i.e. with no free variables /// (as ensured by [Self::validate]), into a monomorphic type. /// /// # Errors @@ -159,14 +159,14 @@ pub(crate) mod test { }; use crate::Extension; - use super::TypeSchemeBase; + use super::PolyFuncTypeBase; lazy_static! { static ref REGISTRY: ExtensionRegistry = ExtensionRegistry::try_new([PRELUDE.to_owned(), EXTENSION.to_owned()]).unwrap(); } - impl TypeSchemeBase { + impl PolyFuncTypeBase { fn new_validated( params: impl Into>, body: FuncTypeBase, @@ -183,7 +183,7 @@ pub(crate) mod test { let list_def = EXTENSION.get_type(&LIST_TYPENAME).unwrap(); let tyvar = TypeArg::new_var_use(0, TypeBound::Any.into()); let list_of_var = Type::new_extension(list_def.instantiate([tyvar.clone()])?); - let list_len = TypeSchemeBase::new_validated( + let list_len = PolyFuncTypeBase::new_validated( [TypeBound::Any.into()], FunctionType::new(vec![list_of_var], vec![USIZE_T]), ®ISTRY, @@ -214,7 +214,7 @@ pub(crate) mod test { // Valid schema... let good_array = Type::new_extension(ar_def.instantiate([tyvar.clone(), szvar.clone()])?); - let good_ts = TypeSchemeBase::new_validated( + let good_ts = PolyFuncTypeBase::new_validated( typarams.clone(), FunctionType::new_endo(good_array), &PRELUDE_REGISTRY, @@ -256,7 +256,7 @@ pub(crate) mod test { PRELUDE_ID, TypeBound::Any, )); - let bad_ts = TypeSchemeBase::new_validated( + let bad_ts = PolyFuncTypeBase::new_validated( typarams.clone(), FunctionType::new_endo(bad_array), &PRELUDE_REGISTRY, @@ -283,7 +283,7 @@ pub(crate) mod test { }, ] { let invalid_ts = - TypeSchemeBase::new_validated([decl.clone()], body_type.clone(), ®ISTRY); + PolyFuncTypeBase::new_validated([decl.clone()], body_type.clone(), ®ISTRY); assert_eq!( invalid_ts.err(), Some(SignatureError::TypeVarDoesNotMatchDeclaration { @@ -293,7 +293,7 @@ pub(crate) mod test { ); } // Variable not declared at all - let invalid_ts = TypeSchemeBase::new_validated([], body_type, ®ISTRY); + let invalid_ts = PolyFuncTypeBase::new_validated([], body_type, ®ISTRY); assert_eq!( invalid_ts.err(), Some(SignatureError::FreeTypeVar { @@ -325,7 +325,7 @@ pub(crate) mod test { let reg = ExtensionRegistry::try_new([e]).unwrap(); let make_scheme = |tp: TypeParam| { - TypeSchemeBase::new_validated( + PolyFuncTypeBase::new_validated( [tp.clone()], FunctionType::new_endo(Type::new_extension(CustomType::new( TYPE_NAME, @@ -390,7 +390,7 @@ pub(crate) mod test { let decl = TypeParam::List { param: Box::new(TP_ANY), }; - let e = TypeSchemeBase::new_validated( + let e = PolyFuncTypeBase::new_validated( [decl.clone()], FunctionTypeRV::new( vec![USIZE_T], @@ -404,7 +404,7 @@ pub(crate) mod test { assert_eq!(cached, TypeParam::List {param: Box::new(TypeParam::Type {b: TypeBound::Copyable})}); }); // Declared as row variable, used as type variable - let e = TypeSchemeBase::new_validated( + let e = PolyFuncTypeBase::new_validated( [decl.clone()], FunctionType::new_endo(vec![Type::new_var_use(0, TypeBound::Any)]), &EMPTY_REG, @@ -419,7 +419,7 @@ pub(crate) mod test { #[test] fn row_variables() { let rty = TypeRV::new_row_var_use(0, TypeBound::Any); - let pf = TypeSchemeBase::new_validated( + let pf = PolyFuncTypeBase::new_validated( [TypeParam::new_list(TP_ANY)], FunctionTypeRV::new( vec![USIZE_T.into(), rty.clone()], @@ -460,7 +460,7 @@ pub(crate) mod test { 0, TypeBound::Copyable, ))); - let pf = TypeSchemeBase::new_validated( + let pf = PolyFuncTypeBase::new_validated( [TypeParam::List { param: Box::new(TypeParam::Type { b: TypeBound::Copyable, diff --git a/hugr-core/src/types/type_param.rs b/hugr-core/src/types/type_param.rs index b6bdc071b..bfc5c04e3 100644 --- a/hugr-core/src/types/type_param.rs +++ b/hugr-core/src/types/type_param.rs @@ -46,11 +46,11 @@ impl UpperBound { } } -/// A *kind* of [TypeArg]. Thus, a parameter declared by a [TypeScheme] or [TypeSchemeRV], +/// A *kind* of [TypeArg]. Thus, a parameter declared by a [PolyFuncType] or [PolyFuncTypeRV], /// specifying a value that must be provided statically in order to instantiate it. /// -/// [TypeScheme]: super::TypeScheme -/// [TypeSchemeRV]: super::TypeSchemeRV +/// [PolyFuncType]: super::PolyFuncType +/// [PolyFuncTypeRV]: super::PolyFuncTypeRV #[derive( Clone, Debug, PartialEq, Eq, derive_more::Display, serde::Deserialize, serde::Serialize, )] diff --git a/hugr-core/src/utils.rs b/hugr-core/src/utils.rs index a67779d80..92c1b3588 100644 --- a/hugr-core/src/utils.rs +++ b/hugr-core/src/utils.rs @@ -112,17 +112,17 @@ pub(crate) mod test_quantum_extension { ops::CustomOp, std_extensions::arithmetic::float_types, type_row, - types::{FunctionType, TypeSchemeRV}, + types::{FunctionType, PolyFuncTypeRV}, Extension, }; use lazy_static::lazy_static; - fn one_qb_func() -> TypeSchemeRV { + fn one_qb_func() -> PolyFuncTypeRV { FunctionTypeRV::new_endo(QB_T).into() } - fn two_qb_func() -> TypeSchemeRV { + fn two_qb_func() -> PolyFuncTypeRV { FunctionTypeRV::new_endo(type_row![QB_T, QB_T]).into() } /// The extension identifier. diff --git a/hugr/src/lib.rs b/hugr/src/lib.rs index 8e6f89ad5..a7b60e1b9 100644 --- a/hugr/src/lib.rs +++ b/hugr/src/lib.rs @@ -43,17 +43,17 @@ //! }, //! ops::{CustomOp, OpName}, //! type_row, -//! types::{FunctionTypeRV, TypeSchemeRV}, +//! types::{FunctionTypeRV, PolyFuncTypeRV}, //! Extension, //! }; //! //! use lazy_static::lazy_static; //! -//! fn one_qb_func() -> TypeSchemeRV { +//! fn one_qb_func() -> PolyFuncTypeRV { //! FunctionTypeRV::new_endo(type_row![QB_T]).into() //! } //! -//! fn two_qb_func() -> TypeSchemeRV { +//! fn two_qb_func() -> PolyFuncTypeRV { //! FunctionTypeRV::new_endo(type_row![QB_T, QB_T]).into() //! } //! /// The extension identifier. From 4a40b9bd04cb6fd5c55f3842d8a47e976d5718f3 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 16 Jul 2024 10:17:22 +0100 Subject: [PATCH 107/115] FunctionTypeRV -> FuncValueType --- hugr-core/src/builder/dataflow.rs | 4 ++-- .../src/extension/declarative/signature.rs | 4 ++-- hugr-core/src/extension/op_def.rs | 8 ++++---- hugr-core/src/extension/prelude.rs | 6 +++--- hugr-core/src/hugr/serialize/test.rs | 10 +++++----- hugr-core/src/hugr/validate/test.rs | 18 +++++++++--------- .../std_extensions/arithmetic/conversions.rs | 6 +++--- .../src/std_extensions/arithmetic/int_ops.rs | 6 +++--- hugr-core/src/std_extensions/collections.rs | 6 +++--- hugr-core/src/std_extensions/logic.rs | 4 ++-- hugr-core/src/types.rs | 10 +++++----- hugr-core/src/types/poly_func.rs | 8 ++++---- hugr-core/src/types/serialize.rs | 6 ++---- hugr-core/src/types/signature.rs | 14 +++++++------- hugr-core/src/utils.rs | 6 +++--- hugr/src/lib.rs | 8 ++++---- 16 files changed, 61 insertions(+), 63 deletions(-) diff --git a/hugr-core/src/builder/dataflow.rs b/hugr-core/src/builder/dataflow.rs index a50289aec..b059069d6 100644 --- a/hugr-core/src/builder/dataflow.rs +++ b/hugr-core/src/builder/dataflow.rs @@ -212,7 +212,7 @@ pub(crate) mod test { use crate::std_extensions::logic::test::and_op; use crate::types::type_param::TypeParam; - use crate::types::{FunctionType, FunctionTypeRV, Type, TypeBound, TypeRV}; + use crate::types::{FuncValueType, FunctionType, Type, TypeBound, TypeRV}; use crate::utils::test_quantum_extension::h_gate; use crate::{ builder::test::{n_identity, BIT, NAT, QB}, @@ -530,7 +530,7 @@ pub(crate) mod test { PolyFuncType::new( [TypeParam::new_list(TypeBound::Copyable)], FunctionType::new( - Type::new_function(FunctionTypeRV::new(USIZE_T, tv.clone())), + Type::new_function(FuncValueType::new(USIZE_T, tv.clone())), vec![], ), ), diff --git a/hugr-core/src/extension/declarative/signature.rs b/hugr-core/src/extension/declarative/signature.rs index 59c44e07b..d1479ae13 100644 --- a/hugr-core/src/extension/declarative/signature.rs +++ b/hugr-core/src/extension/declarative/signature.rs @@ -14,7 +14,7 @@ use smol_str::SmolStr; use crate::extension::prelude::PRELUDE_ID; use crate::extension::{ExtensionSet, SignatureFunc, TypeDef}; use crate::types::type_param::TypeParam; -use crate::types::{CustomType, FunctionTypeRV, PolyFuncTypeRV, Type, TypeRowRV}; +use crate::types::{CustomType, FuncValueType, PolyFuncTypeRV, Type, TypeRowRV}; use crate::Extension; use super::{DeclarationContext, ExtensionDeclarationError}; @@ -50,7 +50,7 @@ impl SignatureDeclaration { Ok(types.into()) }; - let body = FunctionTypeRV { + let body = FuncValueType { input: make_type_row(&self.inputs)?, output: make_type_row(&self.outputs)?, extension_reqs: self.extensions.clone(), diff --git a/hugr-core/src/extension/op_def.rs b/hugr-core/src/extension/op_def.rs index 816e43fb0..67be5ac57 100644 --- a/hugr-core/src/extension/op_def.rs +++ b/hugr-core/src/extension/op_def.rs @@ -11,7 +11,7 @@ use super::{ use crate::ops::{OpName, OpNameRef}; use crate::types::type_param::{check_type_args, TypeArg, TypeParam}; -use crate::types::{FunctionType, FunctionTypeRV, PolyFuncTypeRV}; +use crate::types::{FuncValueType, FunctionType, PolyFuncTypeRV}; use crate::Hugr; /// Trait necessary for binary computations of OpDef signature @@ -192,15 +192,15 @@ impl From for SignatureFunc { } } -impl From for SignatureFunc { - fn from(v: FunctionTypeRV) -> Self { +impl From for SignatureFunc { + fn from(v: FuncValueType) -> Self { Self::PolyFuncType(CustomValidator::from_polyfunc(v)) } } impl From for SignatureFunc { fn from(v: FunctionType) -> Self { - Self::PolyFuncType(CustomValidator::from_polyfunc(FunctionTypeRV::from(v))) + Self::PolyFuncType(CustomValidator::from_polyfunc(FuncValueType::from(v))) } } diff --git a/hugr-core/src/extension/prelude.rs b/hugr-core/src/extension/prelude.rs index 55a2033e6..fd9529c46 100644 --- a/hugr-core/src/extension/prelude.rs +++ b/hugr-core/src/extension/prelude.rs @@ -4,7 +4,7 @@ use lazy_static::lazy_static; use crate::ops::constant::{CustomCheckFailure, ValueName}; use crate::ops::{CustomOp, OpName}; -use crate::types::{FunctionTypeRV, SumType, TypeName}; +use crate::types::{FuncValueType, SumType, TypeName}; use crate::{ extension::{ExtensionId, TypeDefBound}, ops::constant::CustomConst, @@ -32,7 +32,7 @@ impl SignatureFromArgs for ArrayOpCustom { Ok(PolyFuncTypeRV::new( vec![TypeBound::Any.into()], - FunctionTypeRV::new(var_arg_row, other_row), + FuncValueType::new(var_arg_row, other_row), )) } @@ -67,7 +67,7 @@ impl SignatureFromArgs for GenericOpCustom { }; outs.push(ty.clone()); } - Ok(FunctionTypeRV::new(inps, outs).into()) + Ok(FuncValueType::new(inps, outs).into()) } fn static_params(&self) -> &[TypeParam] { diff --git a/hugr-core/src/hugr/serialize/test.rs b/hugr-core/src/hugr/serialize/test.rs index d24e9d8e6..41b22b2c5 100644 --- a/hugr-core/src/hugr/serialize/test.rs +++ b/hugr-core/src/hugr/serialize/test.rs @@ -15,7 +15,7 @@ use crate::std_extensions::arithmetic::int_types::{int_custom_type, ConstInt, IN use crate::std_extensions::logic::NotOp; use crate::types::type_param::TypeParam; use crate::types::{ - FunctionType, FunctionTypeRV, PolyFuncType, PolyFuncTypeRV, SumType, Type, TypeArg, TypeBound, + FuncValueType, FunctionType, PolyFuncType, PolyFuncTypeRV, SumType, Type, TypeArg, TypeBound, TypeRV, }; use crate::{type_row, OutgoingPort}; @@ -440,10 +440,10 @@ fn polyfunctype2() -> PolyFuncTypeRV { let tv1 = TypeRV::new_row_var_use(1, TypeBound::Eq); let params = [TypeBound::Any, TypeBound::Eq].map(TypeParam::new_list); let inputs = vec![ - TypeRV::new_function(FunctionTypeRV::new(tv0.clone(), tv1.clone())), + TypeRV::new_function(FuncValueType::new(tv0.clone(), tv1.clone())), tv0, ]; - let res = PolyFuncTypeRV::new(params, FunctionTypeRV::new(inputs, tv1)); + let res = PolyFuncTypeRV::new(params, FuncValueType::new(inputs, tv1)); // Just check we've got the arguments the right way round // (not that it really matters for the serialization schema we have) res.validate(&EMPTY_REG).unwrap(); @@ -465,14 +465,14 @@ fn roundtrip_polyfunctype_fixedlen(#[case] poly_func_type: PolyFuncType) { } #[rstest] -#[case(FunctionTypeRV::new_endo(type_row![]).into())] +#[case(FuncValueType::new_endo(type_row![]).into())] #[case(PolyFuncTypeRV::new([TypeParam::Opaque { ty: int_custom_type(TypeArg::BoundedNat { n: 1 }) }], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Copyable)])))] #[case(PolyFuncTypeRV::new([TypeBound::Eq.into()], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Eq)])))] #[case(PolyFuncTypeRV::new([TypeParam::new_list(TypeBound::Any)], FunctionType::new_endo(type_row![])))] #[case(PolyFuncTypeRV::new([TypeParam::Tuple { params: [TypeBound::Any.into(), TypeParam::bounded_nat(2.try_into().unwrap())].into() }], FunctionType::new_endo(type_row![])))] #[case(PolyFuncTypeRV::new( [TypeParam::new_list(TypeBound::Any)], - FunctionTypeRV::new_endo(TypeRV::new_row_var_use(0, TypeBound::Any))))] + FuncValueType::new_endo(TypeRV::new_row_var_use(0, TypeBound::Any))))] #[case(polyfunctype2())] fn roundtrip_polyfunctype_varlen(#[case] poly_func_type: PolyFuncTypeRV) { check_testing_roundtrip(poly_func_type) diff --git a/hugr-core/src/hugr/validate/test.rs b/hugr-core/src/hugr/validate/test.rs index 50390cfb3..b85fcb6e6 100644 --- a/hugr-core/src/hugr/validate/test.rs +++ b/hugr-core/src/hugr/validate/test.rs @@ -21,8 +21,8 @@ use crate::std_extensions::logic::test::{and_op, or_op}; use crate::std_extensions::logic::{self, NotOp}; use crate::types::type_param::{TypeArg, TypeArgError}; use crate::types::{ - CustomType, FunctionType, FunctionTypeRV, PolyFuncType, PolyFuncTypeRV, Type, TypeBound, - TypeRV, TypeRow, + CustomType, FuncValueType, FunctionType, PolyFuncType, PolyFuncTypeRV, Type, TypeBound, TypeRV, + TypeRow, }; use crate::{const_extension_ids, test_file, type_row, Direction, IncomingPort, Node}; @@ -579,10 +579,10 @@ pub(crate) fn extension_with_eval_parallel() -> Extension { let inputs = TypeRV::new_row_var_use(0, TypeBound::Any); let outputs = TypeRV::new_row_var_use(1, TypeBound::Any); - let evaled_fn = TypeRV::new_function(FunctionTypeRV::new(inputs.clone(), outputs.clone())); + let evaled_fn = TypeRV::new_function(FuncValueType::new(inputs.clone(), outputs.clone())); let pf = PolyFuncTypeRV::new( [rowp.clone(), rowp.clone()], - FunctionTypeRV::new(vec![evaled_fn, inputs], outputs), + FuncValueType::new(vec![evaled_fn, inputs], outputs), ); e.add_op("eval".into(), "".into(), pf).unwrap(); @@ -591,10 +591,10 @@ pub(crate) fn extension_with_eval_parallel() -> Extension { [rowp.clone(), rowp.clone(), rowp.clone(), rowp.clone()], FunctionType::new( vec![ - Type::new_function(FunctionTypeRV::new(rv(0), rv(2))), - Type::new_function(FunctionTypeRV::new(rv(1), rv(3))), + Type::new_function(FuncValueType::new(rv(0), rv(2))), + Type::new_function(FuncValueType::new(rv(1), rv(3))), ], - Type::new_function(FunctionTypeRV::new(vec![rv(0), rv(1)], vec![rv(2), rv(3)])), + Type::new_function(FuncValueType::new(vec![rv(0), rv(1)], vec![rv(2), rv(3)])), ), ); e.add_op("parallel".into(), "".into(), pf).unwrap(); @@ -644,8 +644,8 @@ fn seq1ty(t: TypeRV) -> TypeArg { 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(FunctionTypeRV::new_endo(tv.clone())); - let ft_usz = Type::new_function(FunctionTypeRV::new_endo(vec![tv.clone(), USIZE_T.into()])); + 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 mut fb = FunctionBuilder::new( "id", PolyFuncType::new( diff --git a/hugr-core/src/std_extensions/arithmetic/conversions.rs b/hugr-core/src/std_extensions/arithmetic/conversions.rs index 924604f26..8f7110807 100644 --- a/hugr-core/src/std_extensions/arithmetic/conversions.rs +++ b/hugr-core/src/std_extensions/arithmetic/conversions.rs @@ -12,7 +12,7 @@ use crate::{ }, ops::{custom::ExtensionOp, NamedOp}, type_row, - types::{FunctionTypeRV, PolyFuncTypeRV, TypeArg, TypeRV}, + types::{FuncValueType, PolyFuncTypeRV, TypeArg, TypeRV}, Extension, }; @@ -48,12 +48,12 @@ impl MakeOpDef for ConvertOpDef { PolyFuncTypeRV::new( vec![LOG_WIDTH_TYPE_PARAM], match self { - trunc_s | trunc_u => FunctionTypeRV::new( + trunc_s | trunc_u => FuncValueType::new( type_row![FLOAT64_TYPE], TypeRV::from(sum_with_error(int_tv(0))), ), convert_s | convert_u => { - FunctionTypeRV::new(vec![int_tv(0)], type_row![FLOAT64_TYPE]) + FuncValueType::new(vec![int_tv(0)], type_row![FLOAT64_TYPE]) } }, ) diff --git a/hugr-core/src/std_extensions/arithmetic/int_ops.rs b/hugr-core/src/std_extensions/arithmetic/int_ops.rs index f15db409c..1718ce9d2 100644 --- a/hugr-core/src/std_extensions/arithmetic/int_ops.rs +++ b/hugr-core/src/std_extensions/arithmetic/int_ops.rs @@ -10,7 +10,7 @@ use crate::ops::custom::ExtensionOp; use crate::ops::{NamedOp, OpName}; use crate::std_extensions::arithmetic::int_types::int_type; use crate::type_row; -use crate::types::{FunctionTypeRV, PolyFuncTypeRV, TypeRowRV}; +use crate::types::{FuncValueType, PolyFuncTypeRV, TypeRowRV}; use crate::utils::collect_array; use crate::{ @@ -162,7 +162,7 @@ impl MakeOpDef for IntOpDef { } itostring_u | itostring_s => PolyFuncTypeRV::new( vec![LOG_WIDTH_TYPE_PARAM], - FunctionTypeRV::new(vec![int_tv(0)], vec![STRING_TYPE]), + FuncValueType::new(vec![int_tv(0)], vec![STRING_TYPE]), ) .into(), } @@ -241,7 +241,7 @@ fn int_polytype( ) -> PolyFuncTypeRV { PolyFuncTypeRV::new( vec![LOG_WIDTH_TYPE_PARAM; n_vars], - FunctionTypeRV::new(input, output), + FuncValueType::new(input, output), ) } diff --git a/hugr-core/src/std_extensions/collections.rs b/hugr-core/src/std_extensions/collections.rs index 315331fdb..0fb809d16 100644 --- a/hugr-core/src/std_extensions/collections.rs +++ b/hugr-core/src/std_extensions/collections.rs @@ -17,7 +17,7 @@ use crate::{ ops::{self, custom::ExtensionOp, NamedOp}, types::{ type_param::{TypeArg, TypeParam}, - CustomCheckFailure, CustomType, FunctionTypeRV, PolyFuncTypeRV, Type, TypeBound, + CustomCheckFailure, CustomType, FuncValueType, PolyFuncTypeRV, Type, TypeBound, }, utils::sorted_consts, Extension, @@ -157,7 +157,7 @@ fn extension() -> Extension { "Pop from back of list".into(), PolyFuncTypeRV::new( vec![TP], - FunctionTypeRV::new(vec![l.clone()], vec![l.clone(), e.clone()]), + FuncValueType::new(vec![l.clone()], vec![l.clone(), e.clone()]), ), ) .unwrap() @@ -166,7 +166,7 @@ fn extension() -> Extension { .add_op( PUSH_NAME, "Push to back of list".into(), - PolyFuncTypeRV::new(vec![TP], FunctionTypeRV::new(vec![l.clone(), e], vec![l])), + PolyFuncTypeRV::new(vec![TP], FuncValueType::new(vec![l.clone(), e], vec![l])), ) .unwrap() .set_constant_folder(PushFold); diff --git a/hugr-core/src/std_extensions/logic.rs b/hugr-core/src/std_extensions/logic.rs index 231cfd455..e571d745d 100644 --- a/hugr-core/src/std_extensions/logic.rs +++ b/hugr-core/src/std_extensions/logic.rs @@ -5,7 +5,7 @@ use strum_macros::{EnumIter, EnumString, IntoStaticStr}; use crate::extension::{ConstFold, ConstFoldResult}; use crate::ops::constant::ValueName; use crate::ops::{OpName, Value}; -use crate::types::{FunctionType, FunctionTypeRV}; +use crate::types::{FuncValueType, FunctionType}; use crate::{ extension::{ prelude::BOOL_T, @@ -168,7 +168,7 @@ fn logic_op_sig() -> impl SignatureFromArgs { return Err(SignatureError::InvalidTypeArgs); }; let var_arg_row = vec![BOOL_T; n as usize]; - Ok(FunctionTypeRV::new(var_arg_row, vec![BOOL_T]).into()) + Ok(FuncValueType::new(var_arg_row, vec![BOOL_T]).into()) } fn static_params(&self) -> &[TypeParam] { diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index 13625eb7d..58c3b57ec 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -17,7 +17,7 @@ use crate::utils::display_list_with_separator; pub use check::SumTypeError; pub use custom::CustomType; pub use poly_func::{PolyFuncType, PolyFuncTypeRV}; -pub use signature::{FunctionType, FunctionTypeRV}; +pub use signature::{FuncValueType, FunctionType}; use smol_str::SmolStr; pub use type_param::TypeArg; pub use type_row::{TypeRow, TypeRowRV}; @@ -225,7 +225,7 @@ pub enum TypeEnum { Alias(AliasDecl), #[allow(missing_docs)] #[display(fmt = "Function({})", "_0")] - Function(Box), + Function(Box), // Index into TypeParams, and cache of TypeBound (checked in validation) #[allow(missing_docs)] #[display(fmt = "Variable({})", _0)] @@ -321,7 +321,7 @@ impl TypeBase { const EMPTY_TYPEROW_REF: &'static TypeRowBase = &Self::EMPTY_TYPEROW; /// Initialize a new function type. - pub fn new_function(fun_ty: impl Into) -> Self { + pub fn new_function(fun_ty: impl Into) -> Self { Self::new(TypeEnum::Function(Box::new(fun_ty.into()))) } @@ -636,7 +636,7 @@ pub(crate) mod test { use crate::proptest::RecursionDepth; use super::{AliasDecl, MaybeRV, TypeBase, TypeBound, TypeEnum}; - use crate::types::{CustomType, FunctionTypeRV, SumType, TypeRowRV}; + use crate::types::{CustomType, FuncValueType, SumType, TypeRowRV}; use ::proptest::prelude::*; impl Arbitrary for super::SumType { @@ -663,7 +663,7 @@ pub(crate) mod test { prop_oneof![ 1 => any::().prop_map(TypeBase::new_alias), 1 => any_with::(depth.into()).prop_map(TypeBase::new_extension), - 1 => any_with::(depth).prop_map(TypeBase::new_function), + 1 => any_with::(depth).prop_map(TypeBase::new_function), 1 => any_with::(depth).prop_map(TypeBase::from), 1 => (any::(), any::()).prop_map(|(i,b)| TypeBase::new_var_use(i,b)), // proptest_derive::Arbitrary's weight attribute requires a constant, diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index 16cf8e346..3368034b6 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -155,7 +155,7 @@ pub(crate) mod test { use crate::types::signature::FuncTypeBase; use crate::types::type_param::{TypeArg, TypeArgError, TypeParam}; use crate::types::{ - CustomType, FunctionType, FunctionTypeRV, MaybeRV, Type, TypeBound, TypeName, TypeRV, + CustomType, FuncValueType, FunctionType, MaybeRV, Type, TypeBound, TypeName, TypeRV, }; use crate::Extension; @@ -392,7 +392,7 @@ pub(crate) mod test { }; let e = PolyFuncTypeBase::new_validated( [decl.clone()], - FunctionTypeRV::new( + FuncValueType::new( vec![USIZE_T], vec![TypeRV::new_row_var_use(0, TypeBound::Copyable)], ), @@ -421,7 +421,7 @@ pub(crate) mod test { let rty = TypeRV::new_row_var_use(0, TypeBound::Any); let pf = PolyFuncTypeBase::new_validated( [TypeParam::new_list(TP_ANY)], - FunctionTypeRV::new( + FuncValueType::new( vec![USIZE_T.into(), rty.clone()], vec![TypeRV::new_tuple(rty)], ), @@ -456,7 +456,7 @@ pub(crate) mod test { #[test] fn row_variables_inner() { - let inner_fty = Type::new_function(FunctionTypeRV::new_endo(TypeRV::new_row_var_use( + let inner_fty = Type::new_function(FuncValueType::new_endo(TypeRV::new_row_var_use( 0, TypeBound::Copyable, ))); diff --git a/hugr-core/src/types/serialize.rs b/hugr-core/src/types/serialize.rs index c557a1e86..de1f94da1 100644 --- a/hugr-core/src/types/serialize.rs +++ b/hugr-core/src/types/serialize.rs @@ -1,6 +1,4 @@ -use super::{ - FunctionTypeRV, MaybeRV, RowVariable, SumType, TypeArg, TypeBase, TypeBound, TypeEnum, -}; +use super::{FuncValueType, MaybeRV, RowVariable, SumType, TypeArg, TypeBase, TypeBound, TypeEnum}; use super::custom::CustomType; @@ -13,7 +11,7 @@ use crate::ops::AliasDecl; pub(super) enum SerSimpleType { Q, I, - G(Box), + G(Box), Sum(SumType), Array { inner: Box, len: u64 }, Opaque(CustomType), diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index 5f56be41e..81fea1be2 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -46,7 +46,7 @@ pub type FunctionType = FuncTypeBase; /// but not a valid node type. /// /// [OpDef]: crate::extension::OpDef -pub type FunctionTypeRV = FuncTypeBase; +pub type FuncValueType = FuncTypeBase; impl FuncTypeBase { /// Builder method, add extension_reqs to an FunctionType @@ -80,7 +80,7 @@ impl FuncTypeBase { } /// True if both inputs and outputs are necessarily empty. - /// (For [FunctionTypeRV], even after any possible substitution of row variables) + /// (For [FuncValueType], even after any possible substitution of row variables) #[inline(always)] pub fn is_empty(&self) -> bool { self.input.is_empty() && self.output.is_empty() @@ -109,8 +109,8 @@ impl FuncTypeBase { } } -impl FunctionTypeRV { - /// If this FunctionTypeRV contains any row variables, return one. +impl FuncValueType { + /// If this FuncValueType contains any row variables, return one. pub fn find_rowvar(&self) -> Option { self.input .iter() @@ -257,17 +257,17 @@ impl Display for FuncTypeBase { } } -impl TryFrom for FunctionType { +impl TryFrom for FunctionType { type Error = SignatureError; - fn try_from(value: FunctionTypeRV) -> Result { + fn try_from(value: FuncValueType) -> Result { let input: TypeRow = value.input.try_into()?; let output: TypeRow = value.output.try_into()?; Ok(Self::new(input, output).with_extension_delta(value.extension_reqs)) } } -impl From for FunctionTypeRV { +impl From for FuncValueType { fn from(value: FunctionType) -> Self { Self { input: value.input.into(), diff --git a/hugr-core/src/utils.rs b/hugr-core/src/utils.rs index 92c1b3588..91aeb046e 100644 --- a/hugr-core/src/utils.rs +++ b/hugr-core/src/utils.rs @@ -103,7 +103,7 @@ pub(crate) fn is_default(t: &T) -> bool { #[cfg(test)] pub(crate) mod test_quantum_extension { use crate::ops::{OpName, OpNameRef}; - use crate::types::FunctionTypeRV; + use crate::types::FuncValueType; use crate::{ extension::{ prelude::{BOOL_T, QB_T}, @@ -119,11 +119,11 @@ pub(crate) mod test_quantum_extension { use lazy_static::lazy_static; fn one_qb_func() -> PolyFuncTypeRV { - FunctionTypeRV::new_endo(QB_T).into() + FuncValueType::new_endo(QB_T).into() } fn two_qb_func() -> PolyFuncTypeRV { - FunctionTypeRV::new_endo(type_row![QB_T, QB_T]).into() + FuncValueType::new_endo(type_row![QB_T, QB_T]).into() } /// The extension identifier. pub const EXTENSION_ID: ExtensionId = ExtensionId::new_unchecked("test.quantum"); diff --git a/hugr/src/lib.rs b/hugr/src/lib.rs index a7b60e1b9..1aee6eeb8 100644 --- a/hugr/src/lib.rs +++ b/hugr/src/lib.rs @@ -43,18 +43,18 @@ //! }, //! ops::{CustomOp, OpName}, //! type_row, -//! types::{FunctionTypeRV, PolyFuncTypeRV}, +//! types::{FuncValueType, PolyFuncTypeRV}, //! Extension, //! }; //! //! use lazy_static::lazy_static; //! //! fn one_qb_func() -> PolyFuncTypeRV { -//! FunctionTypeRV::new_endo(type_row![QB_T]).into() +//! FuncValueType::new_endo(type_row![QB_T]).into() //! } //! //! fn two_qb_func() -> PolyFuncTypeRV { -//! FunctionTypeRV::new_endo(type_row![QB_T, QB_T]).into() +//! FuncValueType::new_endo(type_row![QB_T, QB_T]).into() //! } //! /// The extension identifier. //! pub const EXTENSION_ID: ExtensionId = ExtensionId::new_unchecked("mini.quantum"); @@ -73,7 +73,7 @@ //! .add_op( //! OpName::new_inline("Measure"), //! "Measure a qubit, returning the qubit and the measurement result.".into(), -//! FunctionTypeRV::new(type_row![QB_T], type_row![QB_T, BOOL_T]), +//! FuncValueType::new(type_row![QB_T], type_row![QB_T, BOOL_T]), //! ) //! .unwrap(); //! From dcef178e9405ee4c5375a11c999bd2dc1e4682a8 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 16 Jul 2024 10:44:47 +0100 Subject: [PATCH 108/115] FunctionType -> Signature (take 2) --- hugr-cli/tests/cli.rs | 6 +- hugr-core/src/builder.rs | 25 +++-- hugr-core/src/builder/build_traits.rs | 8 +- hugr-core/src/builder/cfg.rs | 28 +++--- hugr-core/src/builder/circuit.rs | 12 +-- hugr-core/src/builder/conditional.rs | 10 +- hugr-core/src/builder/dataflow.rs | 28 +++--- hugr-core/src/builder/module.rs | 18 ++-- hugr-core/src/builder/tail_loop.rs | 8 +- hugr-core/src/extension.rs | 10 +- hugr-core/src/extension/op_def.rs | 28 +++--- hugr-core/src/extension/prelude.rs | 4 +- hugr-core/src/extension/simple_op.rs | 4 +- hugr-core/src/extension/type_def.rs | 4 +- hugr-core/src/hugr.rs | 12 +-- hugr-core/src/hugr/hugrmut.rs | 4 +- hugr-core/src/hugr/rewrite/consts.rs | 4 +- hugr-core/src/hugr/rewrite/inline_dfg.rs | 4 +- hugr-core/src/hugr/rewrite/outline_cfg.rs | 8 +- hugr-core/src/hugr/rewrite/replace.rs | 17 ++-- hugr-core/src/hugr/rewrite/simple_replace.rs | 9 +- hugr-core/src/hugr/serialize/test.rs | 44 ++++----- hugr-core/src/hugr/validate.rs | 4 +- hugr-core/src/hugr/validate/test.rs | 96 ++++++++----------- hugr-core/src/hugr/views.rs | 6 +- hugr-core/src/hugr/views/descendants.rs | 10 +- hugr-core/src/hugr/views/root_checked.rs | 4 +- hugr-core/src/hugr/views/sibling.rs | 4 +- hugr-core/src/hugr/views/sibling_subgraph.rs | 24 ++--- hugr-core/src/hugr/views/tests.rs | 4 +- hugr-core/src/macros.rs | 4 +- hugr-core/src/ops.rs | 8 +- hugr-core/src/ops/constant.rs | 8 +- hugr-core/src/ops/controlflow.rs | 26 ++--- hugr-core/src/ops/custom.rs | 20 ++-- hugr-core/src/ops/dataflow.rs | 44 ++++----- hugr-core/src/ops/leaf.rs | 22 ++--- hugr-core/src/ops/module.rs | 4 +- .../std_extensions/arithmetic/float_ops.rs | 10 +- .../src/std_extensions/arithmetic/int_ops.rs | 10 +- hugr-core/src/std_extensions/logic.rs | 4 +- hugr-core/src/types.rs | 8 +- hugr-core/src/types/poly_func.rs | 24 ++--- hugr-core/src/types/signature.rs | 12 +-- hugr-core/src/utils.rs | 10 +- hugr-passes/src/const_fold/test.rs | 11 +-- hugr-passes/src/force_order.rs | 4 +- hugr-passes/src/merge_bbs.rs | 4 +- hugr-passes/src/nest_cfgs.rs | 8 +- hugr/benches/benchmarks/hugr.rs | 8 +- hugr/benches/benchmarks/types.rs | 4 +- hugr/src/lib.rs | 2 +- 52 files changed, 338 insertions(+), 364 deletions(-) diff --git a/hugr-cli/tests/cli.rs b/hugr-cli/tests/cli.rs index 1cd8b5438..ac98b2aa7 100644 --- a/hugr-cli/tests/cli.rs +++ b/hugr-cli/tests/cli.rs @@ -12,7 +12,7 @@ use hugr_core::{ builder::{Container, Dataflow, DataflowHugr}, extension::prelude::{BOOL_T, QB_T}, type_row, - types::FunctionType, + types::Signature, Hugr, }; use predicates::{prelude::*, str::contains}; @@ -25,7 +25,7 @@ fn cmd() -> Command { #[fixture] fn test_hugr() -> Hugr { - let df = DFGBuilder::new(FunctionType::new_endo(type_row![BOOL_T])).unwrap(); + let df = DFGBuilder::new(Signature::new_endo(type_row![BOOL_T])).unwrap(); let [i] = df.input_wires_arr(); df.finish_prelude_hugr_with_outputs([i]).unwrap() } @@ -83,7 +83,7 @@ fn test_mermaid(test_hugr_file: NamedTempFile, mut cmd: Command) { #[rstest] fn test_bad_hugr(mut cmd: Command) { - let df = DFGBuilder::new(FunctionType::new_endo(type_row![QB_T])).unwrap(); + let df = DFGBuilder::new(Signature::new_endo(type_row![QB_T])).unwrap(); let bad_hugr = df.hugr().clone(); let bad_hugr_string = serde_json::to_string(&bad_hugr).unwrap(); diff --git a/hugr-core/src/builder.rs b/hugr-core/src/builder.rs index 7502f8275..5f9388da8 100644 --- a/hugr-core/src/builder.rs +++ b/hugr-core/src/builder.rs @@ -30,7 +30,7 @@ //! # use hugr::builder::{BuildError, BuildHandle, Container, DFGBuilder, Dataflow, DataflowHugr, ModuleBuilder, DataflowSubContainer, HugrBuilder}; //! use hugr::extension::prelude::BOOL_T; //! use hugr::std_extensions::logic::{EXTENSION_ID, LOGIC_REG, NotOp}; -//! use hugr::types::FunctionType; +//! use hugr::types::Signature; //! //! # fn doctest() -> Result<(), BuildError> { //! let hugr = { @@ -42,7 +42,7 @@ //! let _dfg_handle = { //! let mut dfg = module_builder.define_function( //! "main", -//! FunctionType::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", -//! FunctionType::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()); @@ -93,7 +93,7 @@ use crate::hugr::ValidationError; use crate::ops::handle::{BasicBlockID, CfgID, ConditionalID, DfgID, FuncID, TailLoopID}; use crate::ops::{NamedOp, OpType}; use crate::types::Type; -use crate::types::{ConstTypeError, FunctionType, TypeRow}; +use crate::types::{ConstTypeError, Signature, TypeRow}; use crate::{Node, Port, Wire}; pub mod handle; @@ -124,14 +124,14 @@ pub use circuit::{CircuitBuildError, CircuitBuilder}; /// Return a FunctionType with the same input and output types (specified) /// whose extension delta, when used in a non-FuncDefn container, will be inferred. -pub fn endo_ft(types: impl Into) -> FunctionType { - FunctionType::new_endo(types).with_extension_delta(TO_BE_INFERRED) +pub fn endo_ft(types: impl Into) -> Signature { + Signature::new_endo(types).with_extension_delta(TO_BE_INFERRED) } /// Return a FunctionType with the specified input and output types /// whose extension delta, when used in a non-FuncDefn container, will be inferred. -pub fn inout_ft(inputs: impl Into, outputs: impl Into) -> FunctionType { - FunctionType::new(inputs, outputs).with_extension_delta(TO_BE_INFERRED) +pub fn inout_ft(inputs: impl Into, outputs: impl Into) -> Signature { + Signature::new(inputs, outputs).with_extension_delta(TO_BE_INFERRED) } #[derive(Debug, Clone, PartialEq, Error)] @@ -236,7 +236,7 @@ pub(crate) mod test { use crate::hugr::{views::HugrView, HugrMut}; use crate::ops; use crate::std_extensions::arithmetic::float_ops::FLOAT_OPS_REGISTRY; - use crate::types::{FunctionType, PolyFuncType, Type}; + use crate::types::{PolyFuncType, Signature, Type}; use crate::{type_row, Hugr}; use super::handle::BuildHandle; @@ -272,8 +272,7 @@ pub(crate) mod test { #[fixture] pub(crate) fn simple_dfg_hugr() -> Hugr { - let dfg_builder = - DFGBuilder::new(FunctionType::new(type_row![BIT], type_row![BIT])).unwrap(); + let dfg_builder = DFGBuilder::new(Signature::new(type_row![BIT], type_row![BIT])).unwrap(); let [i1] = dfg_builder.input_wires_arr(); dfg_builder.finish_prelude_hugr_with_outputs([i1]).unwrap() } @@ -281,7 +280,7 @@ pub(crate) mod test { #[fixture] pub(crate) fn simple_cfg_hugr() -> Hugr { let mut cfg_builder = - CFGBuilder::new(FunctionType::new(type_row![NAT], type_row![NAT])).unwrap(); + CFGBuilder::new(Signature::new(type_row![NAT], type_row![NAT])).unwrap(); super::cfg::test::build_basic_cfg(&mut cfg_builder).unwrap(); cfg_builder.finish_prelude_hugr().unwrap() } @@ -289,7 +288,7 @@ pub(crate) mod test { /// A helper method which creates a DFG rooted hugr with Input and Output node /// only (no wires), given a function type with extension delta. // TODO consider taking two type rows and using TO_BE_INFERRED - pub(crate) fn closed_dfg_root_hugr(signature: FunctionType) -> Hugr { + pub(crate) fn closed_dfg_root_hugr(signature: Signature) -> Hugr { let mut hugr = Hugr::new(ops::DFG { signature: signature.clone(), }); diff --git a/hugr-core/src/builder/build_traits.rs b/hugr-core/src/builder/build_traits.rs index 860ca44c2..e91c36782 100644 --- a/hugr-core/src/builder/build_traits.rs +++ b/hugr-core/src/builder/build_traits.rs @@ -19,7 +19,7 @@ use crate::{ }; use crate::extension::{ExtensionRegistry, ExtensionSet, PRELUDE_REGISTRY, TO_BE_INFERRED}; -use crate::types::{FunctionType, PolyFuncType, Type, TypeArg, TypeRow}; +use crate::types::{PolyFuncType, Signature, Type, TypeArg, TypeRow}; use itertools::Itertools; @@ -274,7 +274,7 @@ pub trait Dataflow: Container { // TODO: Should this be one function, or should there be a temporary "op" one like with the others? fn dfg_builder( &mut self, - signature: FunctionType, + signature: Signature, input_wires: impl IntoIterator, ) -> Result, BuildError> { let op = ops::DFG { @@ -295,7 +295,7 @@ pub trait Dataflow: Container { ) -> Result, BuildError> { let (types, input_wires): (Vec, Vec) = inputs.into_iter().unzip(); self.dfg_builder( - FunctionType::new_endo(types).with_extension_delta(TO_BE_INFERRED), + Signature::new_endo(types).with_extension_delta(TO_BE_INFERRED), input_wires, ) } @@ -323,7 +323,7 @@ pub trait Dataflow: Container { let (cfg_node, _) = add_node_with_wires( self, ops::CFG { - signature: FunctionType::new(inputs.clone(), output_types.clone()) + signature: Signature::new(inputs.clone(), output_types.clone()) .with_extension_delta(extension_delta), }, input_wires, diff --git a/hugr-core/src/builder/cfg.rs b/hugr-core/src/builder/cfg.rs index 0d37992d0..4d8860615 100644 --- a/hugr-core/src/builder/cfg.rs +++ b/hugr-core/src/builder/cfg.rs @@ -11,7 +11,7 @@ use crate::{ }; use crate::{ extension::{ExtensionRegistry, ExtensionSet}, - types::FunctionType, + types::Signature, }; use crate::{hugr::views::HugrView, types::TypeRow}; @@ -49,14 +49,14 @@ use crate::{hugr::HugrMut, type_row, Hugr}; /// builder::{BuildError, CFGBuilder, Container, Dataflow, HugrBuilder, endo_ft, inout_ft}, /// extension::{prelude, ExtensionSet}, /// ops, type_row, -/// types::{FunctionType, SumType, Type}, +/// types::{Signature, SumType, Type}, /// Hugr, /// }; /// /// const NAT: Type = prelude::USIZE_T; /// /// fn make_cfg() -> Result { -/// let mut cfg_builder = CFGBuilder::new(FunctionType::new(type_row![NAT], type_row![NAT]))?; +/// let mut cfg_builder = CFGBuilder::new(Signature::new_endo(NAT))?; /// /// // 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 @@ -151,7 +151,7 @@ impl + AsRef> SubContainer for CFGBuilder { impl CFGBuilder { /// New CFG rooted HUGR builder - pub fn new(signature: FunctionType) -> Result { + pub fn new(signature: Signature) -> Result { let cfg_op = ops::CFG { signature: signature.clone(), }; @@ -272,7 +272,7 @@ impl + AsRef> CFGBuilder { /// This function will return an error if there is an error adding the node. pub fn simple_block_builder( &mut self, - signature: FunctionType, + signature: Signature, n_cases: usize, ) -> Result, BuildError> { self.block_builder_exts( @@ -463,7 +463,7 @@ pub(crate) mod test { let build_result = { let mut module_builder = ModuleBuilder::new(); let mut func_builder = module_builder - .define_function("main", FunctionType::new(vec![NAT], type_row![NAT]))?; + .define_function("main", Signature::new(vec![NAT], type_row![NAT]))?; let _f_id = { let [int] = func_builder.input_wires_arr(); @@ -489,7 +489,7 @@ pub(crate) mod test { } #[test] fn basic_cfg_hugr() -> Result<(), BuildError> { - let mut cfg_builder = CFGBuilder::new(FunctionType::new(type_row![NAT], type_row![NAT]))?; + let mut cfg_builder = CFGBuilder::new(Signature::new(type_row![NAT], type_row![NAT]))?; build_basic_cfg(&mut cfg_builder)?; assert_matches!(cfg_builder.finish_prelude_hugr(), Ok(_)); @@ -511,8 +511,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(FunctionType::new(type_row![NAT], type_row![NAT]), 1)?; + let mut middle_b = + cfg_builder.simple_block_builder(Signature::new(type_row![NAT], type_row![NAT]), 1)?; let middle = { let c = middle_b.add_load_const(ops::Value::unary_unit_sum()); let [inw] = middle_b.input_wires_arr(); @@ -526,7 +526,7 @@ pub(crate) mod test { } #[test] fn test_dom_edge() -> Result<(), BuildError> { - let mut cfg_builder = CFGBuilder::new(FunctionType::new(type_row![NAT], type_row![NAT]))?; + let mut cfg_builder = CFGBuilder::new(Signature::new(type_row![NAT], type_row![NAT]))?; let sum_tuple_const = cfg_builder.add_constant(ops::Value::unary_unit_sum()); let sum_variants = vec![type_row![]]; @@ -542,7 +542,7 @@ pub(crate) mod test { entry_b.finish_with_outputs(sum, [])? }; let mut middle_b = - cfg_builder.simple_block_builder(FunctionType::new(type_row![], type_row![NAT]), 1)?; + cfg_builder.simple_block_builder(Signature::new(type_row![], type_row![NAT]), 1)?; let middle = { let c = middle_b.load_const(&sum_tuple_const); middle_b.finish_with_outputs(c, [inw])? @@ -557,11 +557,11 @@ pub(crate) mod test { #[test] fn test_non_dom_edge() -> Result<(), BuildError> { - let mut cfg_builder = CFGBuilder::new(FunctionType::new(type_row![NAT], type_row![NAT]))?; + let mut cfg_builder = CFGBuilder::new(Signature::new(type_row![NAT], type_row![NAT]))?; 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(FunctionType::new(type_row![NAT], type_row![NAT]), 1)?; + let mut middle_b = + cfg_builder.simple_block_builder(Signature::new(type_row![NAT], type_row![NAT]), 1)?; let [inw] = middle_b.input_wires_arr(); let middle = { let c = middle_b.load_const(&sum_tuple_const); diff --git a/hugr-core/src/builder/circuit.rs b/hugr-core/src/builder/circuit.rs index 272ddead5..c9f92466b 100644 --- a/hugr-core/src/builder/circuit.rs +++ b/hugr-core/src/builder/circuit.rs @@ -254,13 +254,13 @@ mod test { extension::prelude::BOOL_T, ops::{custom::OpaqueOp, CustomOp}, type_row, - types::FunctionType, + types::Signature, }; #[test] fn simple_linear() { let build_res = build_main( - FunctionType::new(type_row![QB, QB], type_row![QB, QB]) + Signature::new(type_row![QB, QB], type_row![QB, QB]) .with_extension_delta(test_quantum_extension::EXTENSION_ID) .with_extension_delta(float_types::EXTENSION_ID) .into(), @@ -300,10 +300,10 @@ mod test { "MyOp", "unknown op".to_string(), vec![], - FunctionType::new(vec![QB, NAT], vec![QB]), + Signature::new(vec![QB, NAT], vec![QB]), )); let build_res = build_main( - FunctionType::new(type_row![QB, QB, NAT], type_row![QB, QB, BOOL_T]) + Signature::new(type_row![QB, QB, NAT], type_row![QB, QB, BOOL_T]) .with_extension_delta(test_quantum_extension::EXTENSION_ID) .into(), |mut f_build| { @@ -330,7 +330,7 @@ mod test { #[test] fn ancillae() { let build_res = build_main( - FunctionType::new_endo(QB) + Signature::new_endo(QB) .with_extension_delta(test_quantum_extension::EXTENSION_ID) .into(), |mut f_build| { @@ -368,7 +368,7 @@ mod test { #[test] fn circuit_builder_errors() { let _build_res = build_main( - FunctionType::new_endo(type_row![QB, QB]).into(), + Signature::new_endo(type_row![QB, QB]).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 bfdd859a5..e4e56cdc1 100644 --- a/hugr-core/src/builder/conditional.rs +++ b/hugr-core/src/builder/conditional.rs @@ -1,7 +1,7 @@ use crate::extension::ExtensionRegistry; use crate::hugr::views::HugrView; use crate::ops::dataflow::DataflowOpTrait; -use crate::types::{FunctionType, TypeRow}; +use crate::types::{Signature, TypeRow}; use crate::ops; use crate::ops::handle::CaseID; @@ -118,7 +118,7 @@ impl + AsRef> ConditionalBuilder { let outputs = cond.outputs; let case_op = ops::Case { - signature: FunctionType::new(inputs.clone(), outputs.clone()) + signature: Signature::new(inputs.clone(), outputs.clone()) .with_extension_delta(extension_delta.clone()), }; let case_node = @@ -134,7 +134,7 @@ impl + AsRef> ConditionalBuilder { let dfg_builder = DFGBuilder::create_with_io( self.hugr_mut(), case_node, - FunctionType::new(inputs, outputs).with_extension_delta(extension_delta), + Signature::new(inputs, outputs).with_extension_delta(extension_delta), )?; Ok(CaseBuilder::from_dfg_builder(dfg_builder)) @@ -186,7 +186,7 @@ impl ConditionalBuilder { impl CaseBuilder { /// Initialize a Case rooted HUGR - pub fn new(signature: FunctionType) -> Result { + pub fn new(signature: Signature) -> Result { let op = ops::Case { signature: signature.clone(), }; @@ -233,7 +233,7 @@ mod test { let build_result: Result = { let mut module_builder = ModuleBuilder::new(); let mut fbuild = module_builder - .define_function("main", FunctionType::new(type_row![NAT], type_row![NAT]))?; + .define_function("main", Signature::new(type_row![NAT], type_row![NAT]))?; let tru_const = fbuild.add_constant(Value::true_val()); let _fdef = { let const_wire = fbuild.load_const(&tru_const); diff --git a/hugr-core/src/builder/dataflow.rs b/hugr-core/src/builder/dataflow.rs index a92953692..267e47a0f 100644 --- a/hugr-core/src/builder/dataflow.rs +++ b/hugr-core/src/builder/dataflow.rs @@ -7,7 +7,7 @@ use std::marker::PhantomData; use crate::hugr::{HugrView, ValidationError}; use crate::ops; -use crate::types::{FunctionType, PolyFuncType}; +use crate::types::{PolyFuncType, Signature}; use crate::extension::ExtensionRegistry; use crate::Node; @@ -26,7 +26,7 @@ impl + AsRef> DFGBuilder { pub(super) fn create_with_io( mut base: T, parent: Node, - signature: FunctionType, + signature: Signature, ) -> Result { let num_in_wires = signature.input().len(); let num_out_wires = signature.output().len(); @@ -67,7 +67,7 @@ impl DFGBuilder { /// # Errors /// /// Error in adding DFG child nodes. - pub fn new(signature: FunctionType) -> Result, BuildError> { + pub fn new(signature: Signature) -> Result, BuildError> { let dfg_op = ops::DFG { signature: signature.clone(), }; @@ -214,7 +214,7 @@ pub(crate) mod test { use crate::std_extensions::logic::test::and_op; use crate::types::type_param::TypeParam; - use crate::types::{FuncValueType, FunctionType, Type, TypeBound, TypeRV}; + use crate::types::{FuncValueType, Signature, Type, TypeBound, TypeRV}; use crate::utils::test_quantum_extension::h_gate; use crate::{ builder::test::{n_identity, BIT, NAT, QB}, @@ -298,7 +298,7 @@ pub(crate) mod test { let mut module_builder = ModuleBuilder::new(); let f_build = module_builder - .define_function("main", FunctionType::new(type_row![QB], type_row![QB, QB]))?; + .define_function("main", Signature::new(type_row![QB], type_row![QB, QB]))?; let [q1] = f_build.input_wires_arr(); f_build.finish_with_outputs([q1, q1])?; @@ -320,14 +320,14 @@ pub(crate) mod test { fn simple_inter_graph_edge() { let builder = || -> Result { let mut f_build = - FunctionBuilder::new("main", FunctionType::new(type_row![BIT], type_row![BIT]))?; + FunctionBuilder::new("main", Signature::new(type_row![BIT], type_row![BIT]))?; let [i1] = f_build.input_wires_arr(); let noop = f_build.add_dataflow_op(Noop { ty: BIT }, [i1])?; let i1 = noop.out_wire(0); let mut nested = - f_build.dfg_builder(FunctionType::new(type_row![], type_row![BIT]), [])?; + f_build.dfg_builder(Signature::new(type_row![], type_row![BIT]), [])?; let id = nested.add_dataflow_op(Noop { ty: BIT }, [i1])?; @@ -342,13 +342,13 @@ pub(crate) mod test { #[test] fn error_on_linear_inter_graph_edge() -> Result<(), BuildError> { let mut f_build = - FunctionBuilder::new("main", FunctionType::new(type_row![QB], type_row![QB]))?; + FunctionBuilder::new("main", Signature::new(type_row![QB], type_row![QB]))?; let [i1] = f_build.input_wires_arr(); let noop = f_build.add_dataflow_op(Noop { ty: QB }, [i1])?; let i1 = noop.out_wire(0); - let mut nested = f_build.dfg_builder(FunctionType::new(type_row![], type_row![QB]), [])?; + let mut nested = f_build.dfg_builder(Signature::new(type_row![], type_row![QB]), [])?; let id_res = nested.add_dataflow_op(Noop { ty: QB }, [i1]); @@ -374,7 +374,7 @@ pub(crate) mod test { #[test] fn insert_hugr() -> Result<(), BuildError> { // Create a simple DFG - let mut dfg_builder = DFGBuilder::new(FunctionType::new(type_row![BIT], type_row![BIT]))?; + let mut dfg_builder = DFGBuilder::new(Signature::new(type_row![BIT], type_row![BIT]))?; 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)?; @@ -384,7 +384,7 @@ pub(crate) mod test { let (dfg_node, f_node) = { let mut f_build = module_builder - .define_function("main", FunctionType::new(type_row![BIT], type_row![BIT]))?; + .define_function("main", Signature::new(type_row![BIT], type_row![BIT]))?; let [i1] = f_build.input_wires_arr(); let dfg = f_build.add_hugr_with_wires(dfg_hugr, [i1])?; @@ -460,7 +460,7 @@ pub(crate) mod test { #[test] fn non_cfg_ancestor() -> Result<(), BuildError> { - let unit_sig = FunctionType::new(type_row![Type::UNIT], type_row![Type::UNIT]); + let unit_sig = Signature::new(type_row![Type::UNIT], type_row![Type::UNIT]); let mut b = DFGBuilder::new(unit_sig.clone())?; let b_child = b.dfg_builder(unit_sig.clone(), [b.input().out_wire(0)])?; let b_child_in_wire = b_child.input().out_wire(0); @@ -484,7 +484,7 @@ pub(crate) mod test { #[test] fn no_relation_edge() -> Result<(), BuildError> { - let unit_sig = FunctionType::new(type_row![Type::UNIT], type_row![Type::UNIT]); + let unit_sig = Signature::new(type_row![Type::UNIT], type_row![Type::UNIT]); let mut b = DFGBuilder::new(unit_sig.clone())?; let mut b_child = b.dfg_builder(unit_sig.clone(), [b.input().out_wire(0)])?; let b_child_child = b_child.dfg_builder(unit_sig.clone(), [b_child.input().out_wire(0)])?; @@ -518,7 +518,7 @@ pub(crate) mod test { "bad_eval", PolyFuncType::new( [TypeParam::new_list(TypeBound::Copyable)], - FunctionType::new( + Signature::new( Type::new_function(FuncValueType::new(USIZE_T, tv.clone())), vec![], ), diff --git a/hugr-core/src/builder/module.rs b/hugr-core/src/builder/module.rs index a57acc76b..d2f144e04 100644 --- a/hugr-core/src/builder/module.rs +++ b/hugr-core/src/builder/module.rs @@ -166,7 +166,7 @@ mod test { }, extension::{EMPTY_REG, PRELUDE_REGISTRY}, type_row, - types::FunctionType, + types::Signature, }; use super::*; @@ -177,7 +177,7 @@ mod test { let f_id = module_builder.declare( "main", - FunctionType::new(type_row![NAT], type_row![NAT]).into(), + Signature::new(type_row![NAT], type_row![NAT]).into(), )?; let mut f_build = module_builder.define_declaration(&f_id)?; @@ -200,7 +200,7 @@ mod test { let f_build = module_builder.define_function( "main", - FunctionType::new( + Signature::new( vec![qubit_state_type.get_alias_type()], vec![qubit_state_type.get_alias_type()], ), @@ -217,14 +217,10 @@ mod test { let build_result = { let mut module_builder = ModuleBuilder::new(); - let mut f_build = module_builder.define_function( - "main", - FunctionType::new(type_row![NAT], type_row![NAT, NAT]), - )?; - let local_build = f_build.define_function( - "local", - FunctionType::new(type_row![NAT], type_row![NAT, NAT]), - )?; + 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 [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 4d29ff840..c7d5544e1 100644 --- a/hugr-core/src/builder/tail_loop.rs +++ b/hugr-core/src/builder/tail_loop.rs @@ -2,7 +2,7 @@ use crate::extension::ExtensionSet; use crate::ops; use crate::hugr::views::HugrView; -use crate::types::{FunctionType, TypeRow}; +use crate::types::{Signature, TypeRow}; use crate::{Hugr, Node}; use super::build_traits::SubContainer; @@ -21,7 +21,7 @@ impl + AsRef> TailLoopBuilder { loop_node: Node, tail_loop: &ops::TailLoop, ) -> Result { - let signature = FunctionType::new(tail_loop.body_input_row(), tail_loop.body_output_row()); + let signature = Signature::new(tail_loop.body_input_row(), tail_loop.body_output_row()); let dfg_build = DFGBuilder::create_with_io(base, loop_node, signature)?; Ok(TailLoopBuilder::from_dfg_builder(dfg_build)) @@ -102,7 +102,7 @@ mod test { hugr::ValidationError, ops::Value, type_row, - types::FunctionType, + types::Signature, }; use super::*; @@ -129,7 +129,7 @@ mod test { let mut module_builder = ModuleBuilder::new(); let mut fbuild = module_builder.define_function( "main", - FunctionType::new(type_row![BIT], type_row![NAT]).with_extension_delta(PRELUDE_ID), + Signature::new(type_row![BIT], type_row![NAT]).with_extension_delta(PRELUDE_ID), )?; let _fdef = { let [b1] = fbuild diff --git a/hugr-core/src/extension.rs b/hugr-core/src/extension.rs index 964797649..9f59c9106 100644 --- a/hugr-core/src/extension.rs +++ b/hugr-core/src/extension.rs @@ -18,7 +18,7 @@ use crate::ops::{self, OpName, OpNameRef}; use crate::types::type_param::{TypeArg, TypeArgError, TypeParam}; use crate::types::RowVariable; use crate::types::{check_typevar_decl, CustomType, Substitution, TypeBound, TypeName}; -use crate::types::{FunctionType, TypeNameRef}; +use crate::types::{Signature, TypeNameRef}; mod op_def; pub use op_def::{ @@ -166,8 +166,8 @@ pub enum SignatureError { "Incorrect result of type application in Call - cached {cached} but expected {expected}" )] CallIncorrectlyAppliesType { - cached: FunctionType, - expected: FunctionType, + cached: Signature, + expected: Signature, }, /// The result of the type application stored in a [LoadFunction] /// is not what we get by applying the type-args to the polymorphic function @@ -177,8 +177,8 @@ pub enum SignatureError { "Incorrect result of type application in LoadFunction - cached {cached} but expected {expected}" )] LoadFunctionIncorrectlyAppliesType { - cached: FunctionType, - expected: FunctionType, + cached: Signature, + expected: Signature, }, } diff --git a/hugr-core/src/extension/op_def.rs b/hugr-core/src/extension/op_def.rs index fe87fbff4..2ec8af05f 100644 --- a/hugr-core/src/extension/op_def.rs +++ b/hugr-core/src/extension/op_def.rs @@ -11,7 +11,7 @@ use super::{ use crate::ops::{OpName, OpNameRef}; use crate::types::type_param::{check_type_args, TypeArg, TypeParam}; -use crate::types::{FuncValueType, FunctionType, PolyFuncTypeRV}; +use crate::types::{FuncValueType, PolyFuncTypeRV, Signature}; use crate::Hugr; /// Trait necessary for binary computations of OpDef signature @@ -198,8 +198,8 @@ impl From for SignatureFunc { } } -impl From for SignatureFunc { - fn from(v: FunctionType) -> Self { +impl From for SignatureFunc { + fn from(v: Signature) -> Self { Self::PolyFuncType(CustomValidator::from_polyfunc(FuncValueType::from(v))) } } @@ -234,7 +234,7 @@ impl SignatureFunc { def: &OpDef, args: &[TypeArg], exts: &ExtensionRegistry, - ) -> Result { + ) -> Result { let temp: PolyFuncTypeRV; // to keep alive let (pf, args) = match &self { SignatureFunc::PolyFuncType(custom) => { @@ -362,7 +362,7 @@ impl OpDef { &self, args: &[TypeArg], exts: &ExtensionRegistry, - ) -> Result { + ) -> Result { self.signature_func.compute_signature(self, args, exts) } @@ -494,7 +494,7 @@ pub(super) mod test { use crate::ops::{CustomOp, OpName}; use crate::std_extensions::collections::{EXTENSION, LIST_TYPENAME}; use crate::types::type_param::{TypeArgError, TypeParam}; - use crate::types::{FunctionType, PolyFuncTypeRV, Type, TypeArg, TypeBound, TypeRV}; + use crate::types::{PolyFuncTypeRV, Signature, Type, TypeArg, TypeBound, TypeRV}; use crate::{const_extension_ids, Extension}; const_extension_ids! { @@ -590,7 +590,7 @@ pub(super) mod test { let list_of_var = Type::new_extension(list_def.instantiate(vec![TypeArg::new_var_use(0, TP)])?); const OP_NAME: OpName = OpName::new_inline("Reverse"); - let type_scheme = PolyFuncTypeRV::new(vec![TP], FunctionType::new_endo(vec![list_of_var])); + let type_scheme = PolyFuncTypeRV::new(vec![TP], Signature::new_endo(vec![list_of_var])); let def = e.add_op(OP_NAME, "desc".into(), type_scheme)?; def.add_lower_func(LowerFunc::FixedHugr { @@ -643,7 +643,7 @@ pub(super) mod test { .collect(); Ok(PolyFuncTypeRV::new( vec![TP.to_owned()], - FunctionType::new(tvs.clone(), vec![Type::new_tuple(tvs)]), + Signature::new(tvs.clone(), vec![Type::new_tuple(tvs)]), )) } @@ -661,7 +661,7 @@ pub(super) mod test { assert_eq!( def.compute_signature(&args, &PRELUDE_REGISTRY), Ok( - FunctionType::new(vec![USIZE_T; 3], vec![Type::new_tuple(vec![USIZE_T; 3])]) + Signature::new(vec![USIZE_T; 3], vec![Type::new_tuple(vec![USIZE_T; 3])]) .with_extension_delta(EXT_ID) ) ); @@ -674,7 +674,7 @@ pub(super) mod test { assert_eq!( def.compute_signature(&args, &PRELUDE_REGISTRY), Ok( - FunctionType::new(tyvars.clone(), vec![Type::new_tuple(tyvars)]) + Signature::new(tyvars.clone(), vec![Type::new_tuple(tyvars)]) .with_extension_delta(EXT_ID) ) ); @@ -720,7 +720,7 @@ pub(super) mod test { "".into(), PolyFuncTypeRV::new( vec![TypeBound::Any.into()], - FunctionType::new_endo(vec![Type::new_var_use(0, TypeBound::Any)]), + Signature::new_endo(vec![Type::new_var_use(0, TypeBound::Any)]), ), )?; let tv = Type::new_var_use(1, TypeBound::Eq); @@ -729,7 +729,7 @@ pub(super) mod test { def.validate_args(&args, &EMPTY_REG, &decls).unwrap(); assert_eq!( def.compute_signature(&args, &EMPTY_REG), - Ok(FunctionType::new_endo(tv).with_extension_delta(EXT_ID)) + Ok(Signature::new_endo(tv).with_extension_delta(EXT_ID)) ); // But not with an external row variable let arg: TypeArg = TypeRV::new_row_var_use(0, TypeBound::Eq).into(); @@ -753,7 +753,7 @@ pub(super) mod test { let params: Vec = vec![TypeParam::Extensions]; let db_set = ExtensionSet::type_var(0); - let fun_ty = FunctionType::new_endo(BOOL_T).with_extension_delta(db_set); + let fun_ty = Signature::new_endo(BOOL_T).with_extension_delta(db_set); let def = e.add_op( "SimpleOp".into(), @@ -763,7 +763,7 @@ pub(super) mod test { // Concrete extension set let es = ExtensionSet::singleton(&EXT_ID); - let exp_fun_ty = FunctionType::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/prelude.rs b/hugr-core/src/extension/prelude.rs index 9aac8d2c8..89ce1e906 100644 --- a/hugr-core/src/extension/prelude.rs +++ b/hugr-core/src/extension/prelude.rs @@ -11,7 +11,7 @@ use crate::{ type_row, types::{ type_param::{TypeArg, TypeParam}, - CustomType, FunctionType, PolyFuncTypeRV, Type, TypeBound, + CustomType, PolyFuncTypeRV, Signature, Type, TypeBound, }, Extension, }; @@ -106,7 +106,7 @@ lazy_static! { prelude.add_op( PRINT_OP_ID, "Print the string to standard output".to_string(), - FunctionType::new(type_row![STRING_TYPE], type_row![]), + Signature::new(type_row![STRING_TYPE], type_row![]), ) .unwrap(); prelude.add_type( diff --git a/hugr-core/src/extension/simple_op.rs b/hugr-core/src/extension/simple_op.rs index c77ed5edc..4d3703f21 100644 --- a/hugr-core/src/extension/simple_op.rs +++ b/hugr-core/src/extension/simple_op.rs @@ -240,7 +240,7 @@ impl From for OpType { #[cfg(test)] mod test { - use crate::{const_extension_ids, type_row, types::FunctionType}; + use crate::{const_extension_ids, type_row, types::Signature}; use super::*; use lazy_static::lazy_static; @@ -253,7 +253,7 @@ mod test { impl MakeOpDef for DummyEnum { fn signature(&self) -> SignatureFunc { - FunctionType::new_endo(type_row![]).into() + Signature::new_endo(type_row![]).into() } fn from_def(_op_def: &OpDef) -> Result { diff --git a/hugr-core/src/extension/type_def.rs b/hugr-core/src/extension/type_def.rs index 68b4ec3e0..9e0c8753b 100644 --- a/hugr-core/src/extension/type_def.rs +++ b/hugr-core/src/extension/type_def.rs @@ -167,7 +167,7 @@ mod test { use crate::extension::SignatureError; use crate::std_extensions::arithmetic::float_types::FLOAT64_TYPE; use crate::types::type_param::{TypeArg, TypeArgError, TypeParam}; - use crate::types::{FunctionType, Type, TypeBound}; + use crate::types::{Signature, Type, TypeBound}; use super::{TypeDef, TypeDefBound}; @@ -184,7 +184,7 @@ mod test { }; let typ = Type::new_extension( def.instantiate(vec![TypeArg::Type { - ty: Type::new_function(FunctionType::new(vec![], vec![])), + ty: Type::new_function(Signature::new(vec![], vec![])), }]) .unwrap(), ); diff --git a/hugr-core/src/hugr.rs b/hugr-core/src/hugr.rs index 7b16c6ff3..fcf358bc2 100644 --- a/hugr-core/src/hugr.rs +++ b/hugr-core/src/hugr.rs @@ -304,7 +304,7 @@ mod test { use crate::extension::{ ExtensionId, ExtensionSet, EMPTY_REG, PRELUDE_REGISTRY, TO_BE_INFERRED, }; - use crate::types::{FunctionType, Type}; + use crate::types::{Signature, Type}; use crate::{const_extension_ids, ops, test_file, type_row}; use rstest::rstest; @@ -435,9 +435,9 @@ mod test { } fn build_ext_dfg(parent: ExtensionSet) -> (Hugr, Node) { - let ty = Type::new_function(FunctionType::new_endo(type_row![])); + let ty = Type::new_function(Signature::new_endo(type_row![])); let mut h = Hugr::new(ops::DFG { - signature: FunctionType::new_endo(ty.clone()).with_extension_delta(parent.clone()), + signature: Signature::new_endo(ty.clone()).with_extension_delta(parent.clone()), }); let root = h.root(); let mid = add_inliftout(&mut h, root, ty); @@ -492,7 +492,7 @@ mod test { #[case] success: bool, #[case] result: impl IntoIterator, ) { - let ty = Type::new_function(FunctionType::new_endo(type_row![])); + let ty = Type::new_function(Signature::new_endo(type_row![])); let grandparent = ExtensionSet::from_iter(grandparent); let result = ExtensionSet::from_iter(result); let root_ty = ops::Conditional { @@ -505,7 +505,7 @@ mod test { let p = h.add_node_with_parent( h.root(), ops::Case { - signature: FunctionType::new_endo(ty.clone()) + signature: Signature::new_endo(ty.clone()) .with_extension_delta(ExtensionSet::from_iter(parent)), }, ); @@ -516,7 +516,7 @@ mod test { if success { assert!(inf_res.is_ok()); let expected_p = ops::Case { - signature: FunctionType::new_endo(ty).with_extension_delta(result.clone()), + signature: Signature::new_endo(ty).with_extension_delta(result.clone()), }; let mut expected = backup; expected.replace_op(p, expected_p).unwrap(); diff --git a/hugr-core/src/hugr/hugrmut.rs b/hugr-core/src/hugr/hugrmut.rs index 08d852249..42b8964a5 100644 --- a/hugr-core/src/hugr/hugrmut.rs +++ b/hugr-core/src/hugr/hugrmut.rs @@ -510,7 +510,7 @@ mod test { extension::PRELUDE_REGISTRY, macros::type_row, ops::{self, dataflow::IOTrait, Noop}, - types::{FunctionType, Type}, + types::{Signature, Type}, }; use super::*; @@ -529,7 +529,7 @@ mod test { module, ops::FuncDefn { name: "main".into(), - signature: FunctionType::new(type_row![NAT], type_row![NAT, NAT]).into(), + signature: Signature::new(type_row![NAT], type_row![NAT, NAT]).into(), }, ); diff --git a/hugr-core/src/hugr/rewrite/consts.rs b/hugr-core/src/hugr/rewrite/consts.rs index fde420bb6..05122af46 100644 --- a/hugr-core/src/hugr/rewrite/consts.rs +++ b/hugr-core/src/hugr/rewrite/consts.rs @@ -121,14 +121,14 @@ mod test { }, ops::{handle::NodeHandle, MakeTuple, Value}, type_row, - types::FunctionType, + types::Signature, }; #[test] fn test_const_remove() -> Result<(), Box> { let mut build = ModuleBuilder::new(); let con_node = build.add_constant(Value::extension(ConstUsize::new(2))); - let mut dfg_build = build.define_function("main", FunctionType::new_endo(type_row![]))?; + let mut dfg_build = build.define_function("main", Signature::new_endo(type_row![]))?; let load_1 = dfg_build.load_const(&con_node); let load_2 = dfg_build.load_const(&con_node); let tup = dfg_build.add_dataflow_op( diff --git a/hugr-core/src/hugr/rewrite/inline_dfg.rs b/hugr-core/src/hugr/rewrite/inline_dfg.rs index 37f3a1cee..b958e1ab8 100644 --- a/hugr-core/src/hugr/rewrite/inline_dfg.rs +++ b/hugr-core/src/hugr/rewrite/inline_dfg.rs @@ -145,7 +145,7 @@ mod test { use crate::std_extensions::arithmetic::float_types; use crate::std_extensions::arithmetic::int_ops::{self, IntOpDef}; use crate::std_extensions::arithmetic::int_types::{self, ConstInt}; - use crate::types::FunctionType; + use crate::types::Signature; use crate::utils::test_quantum_extension; use crate::{type_row, Direction, HugrView, Node, Port}; use crate::{Hugr, Wire}; @@ -251,7 +251,7 @@ mod test { .add_dataflow_op(test_quantum_extension::h_gate(), [p])? .outputs_arr(); let swap = { - let swap = h.dfg_builder(FunctionType::new_endo(type_row![QB_T, QB_T]), [p_h, q])?; + let swap = h.dfg_builder(Signature::new_endo(type_row![QB_T, QB_T]), [p_h, q])?; let [a, b] = swap.input_wires_arr(); swap.finish_with_outputs([b, a])? }; diff --git a/hugr-core/src/hugr/rewrite/outline_cfg.rs b/hugr-core/src/hugr/rewrite/outline_cfg.rs index 1d2ce2ee5..1543be973 100644 --- a/hugr-core/src/hugr/rewrite/outline_cfg.rs +++ b/hugr-core/src/hugr/rewrite/outline_cfg.rs @@ -257,7 +257,7 @@ mod test { use crate::hugr::HugrMut; use crate::ops::constant::Value; use crate::ops::handle::{BasicBlockID, CfgID, ConstID, NodeHandle}; - use crate::types::FunctionType; + use crate::types::Signature; use crate::{type_row, Hugr, HugrView, Node}; use cool_asserts::assert_matches; use itertools::Itertools; @@ -278,7 +278,7 @@ mod test { } impl CondThenLoopCfg { fn new() -> Result { - let block_ty = FunctionType::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()); @@ -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(FunctionType::new_endo(USIZE_T), 2)?, + cfg_builder.simple_block_builder(Signature::new_endo(USIZE_T), 2)?, &pred_const, )?; cfg_builder.branch(&tail, 1, &head)?; @@ -441,7 +441,7 @@ mod test { let mut fbuild = module_builder .define_function( "main", - FunctionType::new(type_row![USIZE_T], type_row![USIZE_T]), + Signature::new(type_row![USIZE_T], type_row![USIZE_T]), ) .unwrap(); let [i1] = fbuild.input_wires_arr(); diff --git a/hugr-core/src/hugr/rewrite/replace.rs b/hugr-core/src/hugr/rewrite/replace.rs index 72bd9e1b9..65daa058f 100644 --- a/hugr-core/src/hugr/rewrite/replace.rs +++ b/hugr-core/src/hugr/rewrite/replace.rs @@ -459,7 +459,7 @@ mod test { use crate::ops::handle::{BasicBlockID, ConstID, NodeHandle}; use crate::ops::{self, Case, DataflowBlock, OpTag, OpType, DFG}; use crate::std_extensions::collections; - use crate::types::{FunctionType, Type, TypeArg, TypeRow}; + use crate::types::{Signature, Type, TypeArg, TypeRow}; use crate::utils::depth; use crate::{type_row, Direction, Hugr, HugrView, OutgoingPort}; @@ -518,7 +518,7 @@ mod test { // Replacement: one BB with two DFGs inside. // Use Hugr rather than Builder because DFGs must be empty (not even Input/Output). let mut replacement = Hugr::new(ops::CFG { - signature: FunctionType::new_endo(just_list.clone()), + signature: Signature::new_endo(just_list.clone()), }); let r_bb = replacement.add_node_with_parent( replacement.root(), @@ -532,17 +532,14 @@ mod test { let r_df1 = replacement.add_node_with_parent( r_bb, DFG { - signature: FunctionType::new( - vec![listy.clone()], - simple_unary_plus(intermed.clone()), - ) - .with_extension_delta(collections::EXTENSION_NAME), + signature: Signature::new(vec![listy.clone()], simple_unary_plus(intermed.clone())) + .with_extension_delta(collections::EXTENSION_NAME), }, ); let r_df2 = replacement.add_node_with_parent( r_bb, DFG { - signature: FunctionType::new(intermed, simple_unary_plus(just_list.clone())) + signature: Signature::new(intermed, simple_unary_plus(just_list.clone())) .with_extension_delta(collections::EXTENSION_NAME), }, ); @@ -644,7 +641,7 @@ mod test { #[test] fn test_invalid() -> Result<(), Box> { - let utou = FunctionType::new_endo(vec![USIZE_T]); + let utou = Signature::new_endo(vec![USIZE_T]); let mk_op = |s| { CustomOp::new_opaque(OpaqueOp::new( ExtensionId::new("unknown_ext").unwrap(), @@ -654,7 +651,7 @@ mod test { utou.clone(), )) }; - let mut h = DFGBuilder::new(FunctionType::new( + let mut h = DFGBuilder::new(Signature::new( type_row![USIZE_T, BOOL_T], type_row![USIZE_T], ))?; diff --git a/hugr-core/src/hugr/rewrite/simple_replace.rs b/hugr-core/src/hugr/rewrite/simple_replace.rs index fb12ff344..d62de1ef3 100644 --- a/hugr-core/src/hugr/rewrite/simple_replace.rs +++ b/hugr-core/src/hugr/rewrite/simple_replace.rs @@ -233,7 +233,7 @@ pub(in crate::hugr::rewrite) mod test { use crate::std_extensions::logic::test::and_op; use crate::std_extensions::logic::NotOp; use crate::type_row; - use crate::types::{FunctionType, Type}; + use crate::types::{Signature, Type}; use crate::utils::test_quantum_extension::{cx_gate, h_gate, EXTENSION_ID}; use crate::{IncomingPort, Node}; @@ -256,7 +256,7 @@ pub(in crate::hugr::rewrite) mod test { let just_q: ExtensionSet = EXTENSION_ID.into(); let mut func_builder = module_builder.define_function( "main", - FunctionType::new_endo(type_row![QB, QB, QB]).with_extension_delta(just_q.clone()), + Signature::new_endo(type_row![QB, QB, QB]).with_extension_delta(just_q.clone()), )?; let [qb0, qb1, qb2] = func_builder.input_wires_arr(); @@ -633,10 +633,7 @@ pub(in crate::hugr::rewrite) mod test { let [_input, output] = hugr.get_io(hugr.root()).unwrap(); let replacement = { - let b = DFGBuilder::new(FunctionType::new( - type_row![BOOL_T], - type_row![BOOL_T, BOOL_T], - ))?; + let b = DFGBuilder::new(Signature::new(type_row![BOOL_T], type_row![BOOL_T, BOOL_T]))?; let [w] = b.input_wires_arr(); b.finish_prelude_hugr_with_outputs([w, w])? }; diff --git a/hugr-core/src/hugr/serialize/test.rs b/hugr-core/src/hugr/serialize/test.rs index ad6bd09e5..9b7da8a4a 100644 --- a/hugr-core/src/hugr/serialize/test.rs +++ b/hugr-core/src/hugr/serialize/test.rs @@ -15,7 +15,7 @@ use crate::std_extensions::arithmetic::int_types::{int_custom_type, ConstInt, IN use crate::std_extensions::logic::NotOp; use crate::types::type_param::TypeParam; use crate::types::{ - FuncValueType, FunctionType, PolyFuncType, PolyFuncTypeRV, SumType, Type, TypeArg, TypeBound, + FuncValueType, PolyFuncType, PolyFuncTypeRV, Signature, SumType, Type, TypeArg, TypeBound, TypeRV, }; use crate::{type_row, OutgoingPort}; @@ -214,7 +214,7 @@ fn gen_optype(g: &MultiPortGraph, node: portgraph::NodeIndex) -> OpType { let outputs = g.num_outputs(node); match (inputs == 0, outputs == 0) { (false, false) => DFG { - signature: FunctionType::new(vec![NAT; inputs - 1], vec![NAT; outputs - 1]), + signature: Signature::new(vec![NAT; inputs - 1], vec![NAT; outputs - 1]), } .into(), (true, false) => Input::new(vec![NAT; outputs - 1]).into(), @@ -268,7 +268,7 @@ fn weighted_hugr_ser() { let t_row = vec![Type::new_sum([type_row![NAT], type_row![QB]])]; let mut f_build = module_builder - .define_function("main", FunctionType::new(t_row.clone(), t_row)) + .define_function("main", Signature::new(t_row.clone(), t_row)) .unwrap(); let outputs = f_build @@ -297,7 +297,7 @@ fn weighted_hugr_ser() { #[test] fn dfg_roundtrip() -> Result<(), Box> { let tp: Vec = vec![BOOL_T; 2]; - let mut dfg = DFGBuilder::new(FunctionType::new(tp.clone(), tp))?; + let mut dfg = DFGBuilder::new(Signature::new(tp.clone(), tp))?; let mut params: [_; 2] = dfg.input_wires_arr(); for p in params.iter_mut() { *p = dfg @@ -336,8 +336,8 @@ fn opaque_ops() -> Result<(), Box> { #[test] fn function_type() -> Result<(), Box> { - let fn_ty = Type::new_function(FunctionType::new_endo(type_row![BOOL_T])); - let mut bldr = DFGBuilder::new(FunctionType::new_endo(vec![fn_ty.clone()]))?; + let fn_ty = Type::new_function(Signature::new_endo(type_row![BOOL_T])); + let mut bldr = DFGBuilder::new(Signature::new_endo(vec![fn_ty.clone()]))?; let op = bldr.add_dataflow_op(Noop { ty: fn_ty }, bldr.input_wires())?; let h = bldr.finish_prelude_hugr_with_outputs(op.outputs())?; @@ -347,7 +347,7 @@ fn function_type() -> Result<(), Box> { #[test] fn hierarchy_order() -> Result<(), Box> { - let mut hugr = closed_dfg_root_hugr(FunctionType::new(vec![QB], vec![QB])); + let mut hugr = closed_dfg_root_hugr(Signature::new(vec![QB], vec![QB])); let [old_in, out] = hugr.get_io(hugr.root()).unwrap(); hugr.connect(old_in, 0, out, 0); @@ -381,7 +381,7 @@ fn constants_roundtrip() -> Result<(), Box> { #[test] fn serialize_types_roundtrip() { - let g: Type = Type::new_function(FunctionType::new_endo(vec![])); + let g: Type = Type::new_function(Signature::new_endo(vec![])); check_testing_roundtrip(g.clone()); // A Simple tuple @@ -404,7 +404,7 @@ fn serialize_types_roundtrip() { #[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(FunctionType::new_endo(type_row![QB_T,BOOL_T,USIZE_T])))] +#[case(Type::new_function(Signature::new_endo(type_row![QB_T,BOOL_T,USIZE_T])))] fn roundtrip_type(#[case] typ: Type) { check_testing_roundtrip(typ); } @@ -431,7 +431,7 @@ fn roundtrip_value(#[case] value: Value) { fn polyfunctype1() -> PolyFuncType { let mut extension_set = ExtensionSet::new(); extension_set.insert_type_var(1); - let function_type = FunctionType::new_endo(type_row![]).with_extension_delta(extension_set); + let function_type = Signature::new_endo(type_row![]).with_extension_delta(extension_set); PolyFuncType::new([TypeParam::max_nat(), TypeParam::Extensions], function_type) } @@ -451,25 +451,25 @@ fn polyfunctype2() -> PolyFuncTypeRV { } #[rstest] -#[case(FunctionType::new_endo(type_row![]).into())] +#[case(Signature::new_endo(type_row![]).into())] #[case(polyfunctype1())] -#[case(PolyFuncType::new([TypeParam::Opaque { ty: int_custom_type(TypeArg::BoundedNat { n: 1 }) }], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Copyable)])))] -#[case(PolyFuncType::new([TypeBound::Eq.into()], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Eq)])))] -#[case(PolyFuncType::new([TypeParam::new_list(TypeBound::Any)], FunctionType::new_endo(type_row![])))] -#[case(PolyFuncType::new([TypeParam::Tuple { params: [TypeBound::Any.into(), TypeParam::bounded_nat(2.try_into().unwrap())].into() }], FunctionType::new_endo(type_row![])))] +#[case(PolyFuncType::new([TypeParam::Opaque { ty: int_custom_type(TypeArg::BoundedNat { n: 1 }) }], Signature::new_endo(type_row![Type::new_var_use(0, TypeBound::Copyable)])))] +#[case(PolyFuncType::new([TypeBound::Eq.into()], Signature::new_endo(type_row![Type::new_var_use(0, TypeBound::Eq)])))] +#[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( [TypeParam::new_list(TypeBound::Any)], - FunctionType::new_endo(Type::new_tuple(TypeRV::new_row_var_use(0, TypeBound::Any)))))] + Signature::new_endo(Type::new_tuple(TypeRV::new_row_var_use(0, TypeBound::Any)))))] fn roundtrip_polyfunctype_fixedlen(#[case] poly_func_type: PolyFuncType) { check_testing_roundtrip(poly_func_type) } #[rstest] #[case(FuncValueType::new_endo(type_row![]).into())] -#[case(PolyFuncTypeRV::new([TypeParam::Opaque { ty: int_custom_type(TypeArg::BoundedNat { n: 1 }) }], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Copyable)])))] -#[case(PolyFuncTypeRV::new([TypeBound::Eq.into()], FunctionType::new_endo(type_row![Type::new_var_use(0, TypeBound::Eq)])))] -#[case(PolyFuncTypeRV::new([TypeParam::new_list(TypeBound::Any)], FunctionType::new_endo(type_row![])))] -#[case(PolyFuncTypeRV::new([TypeParam::Tuple { params: [TypeBound::Any.into(), TypeParam::bounded_nat(2.try_into().unwrap())].into() }], FunctionType::new_endo(type_row![])))] +#[case(PolyFuncTypeRV::new([TypeParam::Opaque { ty: int_custom_type(TypeArg::BoundedNat { n: 1 }) }], FuncValueType::new_endo(type_row![Type::new_var_use(0, TypeBound::Copyable)])))] +#[case(PolyFuncTypeRV::new([TypeBound::Eq.into()], FuncValueType::new_endo(type_row![Type::new_var_use(0, TypeBound::Eq)])))] +#[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( [TypeParam::new_list(TypeBound::Any)], FuncValueType::new_endo(TypeRV::new_row_var_use(0, TypeBound::Any))))] @@ -487,9 +487,9 @@ fn roundtrip_polyfunctype_varlen(#[case] poly_func_type: PolyFuncTypeRV) { #[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::Eq)]))] -#[case(ops::Output::new(vec![Type::new_function(FunctionType::new_endo(type_row![]))]))] +#[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 : FunctionType::new_endo(type_row![BOOL_T]) })] +#[case(ops::CallIndirect { signature : Signature::new_endo(type_row![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/validate.rs b/hugr-core/src/hugr/validate.rs index 3c9e1f18a..7c978262e 100644 --- a/hugr-core/src/hugr/validate.rs +++ b/hugr-core/src/hugr/validate.rs @@ -16,7 +16,7 @@ use crate::ops::custom::{resolve_opaque_op, CustomOp, CustomOpError}; use crate::ops::validate::{ChildrenEdgeData, ChildrenValidationError, EdgeValidationError}; use crate::ops::{FuncDefn, OpParent, OpTag, OpTrait, OpType, ValidateOp}; use crate::types::type_param::TypeParam; -use crate::types::{EdgeKind, FunctionType}; +use crate::types::{EdgeKind, Signature}; use crate::{Direction, Hugr, Node, Port}; use super::views::{HierarchyView, HugrView, SiblingGraph}; @@ -65,7 +65,7 @@ impl Hugr { return Err(ValidationError::ExtensionsNotInferred { node: parent }); } let parent_extensions = match parent_op.inner_function_type() { - Some(FunctionType { extension_reqs, .. }) => extension_reqs, + Some(Signature { extension_reqs, .. }) => extension_reqs, None => match parent_op.tag() { OpTag::Cfg | OpTag::Conditional => parent_op.extension_delta(), // ModuleRoot holds but does not execute its children, so allow any extensions diff --git a/hugr-core/src/hugr/validate/test.rs b/hugr-core/src/hugr/validate/test.rs index c66c9417a..4a9a65c24 100644 --- a/hugr-core/src/hugr/validate/test.rs +++ b/hugr-core/src/hugr/validate/test.rs @@ -21,7 +21,7 @@ use crate::std_extensions::logic::test::{and_op, or_op}; use crate::std_extensions::logic::{self, NotOp}; use crate::types::type_param::{TypeArg, TypeArgError}; use crate::types::{ - CustomType, FuncValueType, FunctionType, PolyFuncType, PolyFuncTypeRV, Type, TypeBound, TypeRV, + CustomType, FuncValueType, PolyFuncType, PolyFuncTypeRV, Signature, Type, TypeBound, TypeRV, TypeRow, }; use crate::{const_extension_ids, test_file, type_row, Direction, IncomingPort, Node}; @@ -34,7 +34,7 @@ const NAT: Type = crate::extension::prelude::USIZE_T; fn make_simple_hugr(copies: usize) -> (Hugr, Node) { let def_op: OpType = ops::FuncDefn { name: "main".into(), - signature: FunctionType::new(type_row![BOOL_T], vec![BOOL_T; copies]).into(), + signature: Signature::new(type_row![BOOL_T], vec![BOOL_T; copies]).into(), } .into(); @@ -108,7 +108,7 @@ fn leaf_root() { #[test] fn dfg_root() { let dfg_op: OpType = ops::DFG { - signature: FunctionType::new_endo(type_row![BOOL_T]), + signature: Signature::new_endo(type_row![BOOL_T]), } .into(); @@ -137,7 +137,7 @@ fn children_restrictions() { .unwrap(); // Add a definition without children - let def_sig = FunctionType::new(type_row![BOOL_T], type_row![BOOL_T, BOOL_T]); + let def_sig = Signature::new(type_row![BOOL_T], type_row![BOOL_T, BOOL_T]); let new_def = b.add_node_with_parent( root, ops::FuncDefn { @@ -210,7 +210,7 @@ fn df_children_restrictions() { #[test] fn test_ext_edge() { let mut h = closed_dfg_root_hugr( - FunctionType::new(type_row![BOOL_T, BOOL_T], type_row![BOOL_T]) + Signature::new(type_row![BOOL_T, BOOL_T], type_row![BOOL_T]) .with_extension_delta(TO_BE_INFERRED), ); let [input, output] = h.get_io(h.root()).unwrap(); @@ -219,8 +219,7 @@ fn test_ext_edge() { let sub_dfg = h.add_node_with_parent( h.root(), ops::DFG { - signature: FunctionType::new_endo(type_row![BOOL_T]) - .with_extension_delta(TO_BE_INFERRED), + signature: Signature::new_endo(type_row![BOOL_T]).with_extension_delta(TO_BE_INFERRED), }, ); // this Xor has its 2nd input unconnected @@ -255,14 +254,11 @@ fn test_ext_edge() { #[test] fn no_ext_edge_into_func() -> Result<(), Box> { - let b2b = FunctionType::new_endo(BOOL_T); - let mut h = DFGBuilder::new(FunctionType::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( - FunctionType::new(vec![], Type::new_function(b2b.clone())), - [], - )?; + let mut dfg = h.dfg_builder(Signature::new(vec![], Type::new_function(b2b.clone())), [])?; let mut func = dfg.define_function("AndWithOuter", b2b.clone())?; let [fn_input] = func.input_wires_arr(); let and_op = func.add_dataflow_op(and_op(), [fn_input, input])?; // 'ext' edge @@ -288,7 +284,7 @@ fn no_ext_edge_into_func() -> Result<(), Box> { #[test] fn test_local_const() { let mut h = - closed_dfg_root_hugr(FunctionType::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); @@ -320,10 +316,7 @@ fn test_local_const() { #[test] fn dfg_with_cycles() { - let mut h = closed_dfg_root_hugr(FunctionType::new( - type_row![BOOL_T, BOOL_T], - type_row![BOOL_T], - )); + let mut h = closed_dfg_root_hugr(Signature::new(type_row![BOOL_T, BOOL_T], type_row![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(), NotOp); @@ -345,7 +338,7 @@ fn identity_hugr_with_type(t: Type) -> (Hugr, Node) { b.root(), ops::FuncDefn { name: "main".into(), - signature: FunctionType::new(row.clone(), row.clone()).into(), + signature: Signature::new(row.clone(), row.clone()).into(), }, ); @@ -468,7 +461,7 @@ fn typevars_declared() -> Result<(), Box> { "myfunc", PolyFuncType::new( [TypeBound::Any.into()], - FunctionType::new_endo(vec![Type::new_var_use(0, TypeBound::Any)]), + Signature::new_endo(vec![Type::new_var_use(0, TypeBound::Any)]), ), )?; let [w] = f.input_wires_arr(); @@ -478,7 +471,7 @@ fn typevars_declared() -> Result<(), Box> { "myfunc", PolyFuncType::new( [TypeBound::Any.into()], - FunctionType::new_endo(vec![Type::new_var_use(1, TypeBound::Any)]), + Signature::new_endo(vec![Type::new_var_use(1, TypeBound::Any)]), ), )?; let [w] = f.input_wires_arr(); @@ -488,7 +481,7 @@ fn typevars_declared() -> Result<(), Box> { "myfunc", PolyFuncType::new( [TypeBound::Any.into()], - FunctionType::new_endo(vec![Type::new_var_use(1, TypeBound::Copyable)]), + Signature::new_endo(vec![Type::new_var_use(1, TypeBound::Copyable)]), ), )?; let [w] = f.input_wires_arr(); @@ -506,12 +499,12 @@ fn nested_typevars() -> Result<(), Box> { "outer", PolyFuncType::new( [OUTER_BOUND.into()], - FunctionType::new_endo(vec![Type::new_var_use(0, TypeBound::Any)]), + Signature::new_endo(vec![Type::new_var_use(0, TypeBound::Any)]), ), )?; let inner = outer.define_function( "inner", - PolyFuncType::new([INNER_BOUND.into()], FunctionType::new_endo(vec![t])), + PolyFuncType::new([INNER_BOUND.into()], Signature::new_endo(vec![t])), )?; let [w] = inner.input_wires_arr(); inner.finish_with_outputs([w])?; @@ -552,7 +545,7 @@ fn no_polymorphic_consts() -> Result<(), Box> { "myfunc", PolyFuncType::new( [BOUND], - FunctionType::new(vec![], vec![list_of_var.clone()]) + Signature::new(vec![], vec![list_of_var.clone()]) .with_extension_delta(collections::EXTENSION_NAME), ), )?; @@ -591,7 +584,7 @@ pub(crate) fn extension_with_eval_parallel() -> Extension { let rv = |idx| TypeRV::new_row_var_use(idx, TypeBound::Any); let pf = PolyFuncTypeRV::new( [rowp.clone(), rowp.clone(), rowp.clone(), rowp.clone()], - FunctionType::new( + Signature::new( vec![ Type::new_function(FuncValueType::new(rv(0), rv(2))), Type::new_function(FuncValueType::new(rv(1), rv(3))), @@ -612,7 +605,7 @@ fn instantiate_row_variables() -> Result<(), Box> { let e = extension_with_eval_parallel(); let mut dfb = DFGBuilder::new(inout_ft( vec![ - Type::new_function(FunctionType::new(USIZE_T, vec![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) @@ -652,21 +645,18 @@ fn row_variables() -> Result<(), Box> { "id", PolyFuncType::new( [TypeParam::new_list(TypeBound::Any)], - FunctionType::new(inner_ft.clone(), ft_usz).with_extension_delta(e.name.clone()), + Signature::new(inner_ft.clone(), ft_usz).with_extension_delta(e.name.clone()), ), )?; // 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", FunctionType::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)?.outputs_arr(); - let loadf = LoadFunction::try_new( - FunctionType::new_endo(USIZE_T).into(), - [], - &PRELUDE_REGISTRY, - ) - .unwrap(); + let loadf = + LoadFunction::try_new(Signature::new_endo(USIZE_T).into(), [], &PRELUDE_REGISTRY) + .unwrap(); fb.add_dataflow_op(loadf, [inner_def])?.outputs_arr() }; let par = e.instantiate_extension_op( @@ -692,7 +682,7 @@ fn test_polymorphic_call() -> Result<(), Box> { TypeBound::Any.into(), ]; let evaled_fn = Type::new_function( - FunctionType::new( + Signature::new( Type::new_var_use(0, TypeBound::Any), Type::new_var_use(2, TypeBound::Any), ) @@ -705,7 +695,7 @@ fn test_polymorphic_call() -> Result<(), Box> { "".into(), PolyFuncTypeRV::new( params.clone(), - FunctionType::new( + Signature::new( vec![evaled_fn, Type::new_var_use(0, TypeBound::Any)], Type::new_var_use(2, TypeBound::Any), ) @@ -714,7 +704,7 @@ fn test_polymorphic_call() -> Result<(), Box> { )?; fn utou(e: impl Into) -> Type { - Type::new_function(FunctionType::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]); @@ -730,7 +720,7 @@ fn test_polymorphic_call() -> Result<(), Box> { "two_ints", PolyFuncType::new( vec![TypeParam::Extensions], - FunctionType::new(vec![utou(es.clone()), int_pair.clone()], int_pair.clone()) + Signature::new(vec![utou(es.clone()), int_pair.clone()], int_pair.clone()) .with_extension_delta(EXT_ID) .with_extension_delta(es.clone()), ), @@ -773,7 +763,7 @@ fn test_polymorphic_call() -> Result<(), Box> { )?; let h = d.finish_hugr_with_outputs(call.outputs(), ®)?; let call_ty = h.get_optype(call.node()).dataflow_signature().unwrap(); - let exp_fun_ty = FunctionType::new(vec![utou(PRELUDE_ID), int_pair.clone()], int_pair) + let exp_fun_ty = Signature::new(vec![utou(PRELUDE_ID), int_pair.clone()], int_pair) .with_extension_delta(EXT_ID) .with_extension_delta(PRELUDE_ID); assert_eq!(call_ty, exp_fun_ty); @@ -787,12 +777,12 @@ fn test_polymorphic_load() -> Result<(), Box> { "id", PolyFuncType::new( vec![TypeBound::Any.into()], - FunctionType::new_endo(vec![Type::new_var_use(0, TypeBound::Any)]), + Signature::new_endo(vec![Type::new_var_use(0, TypeBound::Any)]), ), )?; - let sig = FunctionType::new( + let sig = Signature::new( vec![], - vec![Type::new_function(FunctionType::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)?; @@ -817,7 +807,7 @@ fn cfg_children_restrictions() { b.replace_op( copy, ops::CFG { - signature: FunctionType::new(type_row![BOOL_T], type_row![BOOL_T]), + signature: Signature::new(type_row![BOOL_T], type_row![BOOL_T]), }, ) .unwrap(); @@ -880,7 +870,7 @@ fn cfg_children_restrictions() { b.replace_op( cfg, ops::CFG { - signature: FunctionType::new(type_row![QB_T], type_row![BOOL_T]), + signature: Signature::new(type_row![QB_T], type_row![BOOL_T]), }, ) .unwrap(); @@ -918,14 +908,14 @@ fn cfg_children_restrictions() { fn cfg_connections() -> Result<(), Box> { use crate::builder::CFGBuilder; - let mut hugr = CFGBuilder::new(FunctionType::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 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(FunctionType::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)?; @@ -987,14 +977,13 @@ mod extension_tests { #[case::f1(|ft: FunctionType| ops::FuncDefn {name: "foo".to_string(), signature: ft.into()}.into())] #[case::c1(|signature| ops::Case {signature}.into())] fn parent_extension_mismatch( - #[case] parent_f: impl Fn(FunctionType) -> OpType, + #[case] parent_f: impl Fn(Signature) -> OpType, #[values(ExtensionSet::new(), XA.into())] parent_extensions: ExtensionSet, ) { // Child graph adds extension "XB", but the parent (in all cases) // declares a different delta, causing a mismatch. - let parent = parent_f( - FunctionType::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( @@ -1042,7 +1031,7 @@ mod extension_tests { #[case] success: bool, ) -> Result<(), BuildError> { let mut cfg = CFGBuilder::new( - FunctionType::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 pred = bb.add_load_value(Value::unary_unit_sum()); @@ -1092,8 +1081,7 @@ mod extension_tests { let case = hugr.add_node_with_parent( hugr.root(), ops::Case { - signature: FunctionType::new_endo(USIZE_T) - .with_extension_delta(case_exts.clone()), + signature: Signature::new_endo(USIZE_T).with_extension_delta(case_exts.clone()), }, ); diff --git a/hugr-core/src/hugr/views.rs b/hugr-core/src/hugr/views.rs index 60950ca3d..c8f7ae9e3 100644 --- a/hugr-core/src/hugr/views.rs +++ b/hugr-core/src/hugr/views.rs @@ -32,7 +32,7 @@ use crate::extension::ExtensionRegistry; use crate::ops::handle::NodeHandle; use crate::ops::{OpParent, OpTag, OpTrait, OpType}; -use crate::types::{EdgeKind, FunctionType, PolyFuncType, Type}; +use crate::types::{EdgeKind, PolyFuncType, Signature, Type}; use crate::{Direction, IncomingPort, Node, OutgoingPort, Port}; use itertools::Either; @@ -333,7 +333,7 @@ pub trait HugrView: HugrInternals { /// /// In contrast to [`poly_func_type`][HugrView::poly_func_type], this /// method always return a concrete [`FunctionType`]. - fn inner_function_type(&self) -> Option { + fn inner_function_type(&self) -> Option { self.root_type().inner_function_type() } @@ -430,7 +430,7 @@ pub trait HugrView: HugrInternals { /// Get the "signature" (incoming and outgoing types) of a node, non-Value /// kind ports will be missing. - fn signature(&self, node: Node) -> Option { + fn signature(&self, node: Node) -> Option { self.get_optype(node).dataflow_signature() } diff --git a/hugr-core/src/hugr/views/descendants.rs b/hugr-core/src/hugr/views/descendants.rs index 8b5afa2f1..83a7d6687 100644 --- a/hugr-core/src/hugr/views/descendants.rs +++ b/hugr-core/src/hugr/views/descendants.rs @@ -207,7 +207,7 @@ pub(super) mod test { use crate::{ builder::{Container, Dataflow, DataflowSubContainer, HugrBuilder, ModuleBuilder}, type_row, - types::{FunctionType, Type}, + types::{Signature, Type}, utils::test_quantum_extension::{h_gate, EXTENSION_ID}, }; @@ -226,7 +226,7 @@ pub(super) mod test { let (f_id, inner_id) = { let mut func_builder = module_builder.define_function( "main", - FunctionType::new_endo(type_row![NAT, QB]).with_extension_delta(EXTENSION_ID), + Signature::new_endo(type_row![NAT, QB]).with_extension_delta(EXTENSION_ID), )?; let [int, qb] = func_builder.input_wires_arr(); @@ -235,7 +235,7 @@ pub(super) mod test { let inner_id = { let inner_builder = func_builder - .dfg_builder(FunctionType::new(type_row![NAT], type_row![NAT]), [int])?; + .dfg_builder(Signature::new(type_row![NAT], type_row![NAT]), [int])?; let w = inner_builder.input_wires(); inner_builder.finish_with_outputs(w) }?; @@ -263,7 +263,7 @@ pub(super) mod test { assert_eq!( region.poly_func_type(), Some( - FunctionType::new_endo(type_row![NAT, QB]) + Signature::new_endo(type_row![NAT, QB]) .with_extension_delta(EXTENSION_ID) .into() ) @@ -271,7 +271,7 @@ pub(super) mod test { let inner_region: DescendantsGraph = DescendantsGraph::try_new(&hugr, inner)?; assert_eq!( inner_region.inner_function_type(), - Some(FunctionType::new(type_row![NAT], type_row![NAT])) + Some(Signature::new(type_row![NAT], type_row![NAT])) ); Ok(()) diff --git a/hugr-core/src/hugr/views/root_checked.rs b/hugr-core/src/hugr/views/root_checked.rs index 668fdb83d..94ac05242 100644 --- a/hugr-core/src/hugr/views/root_checked.rs +++ b/hugr-core/src/hugr/views/root_checked.rs @@ -75,12 +75,12 @@ mod test { use crate::hugr::{HugrError, HugrMut}; use crate::ops::handle::{BasicBlockID, CfgID, DataflowParentID, DfgID}; use crate::ops::{DataflowBlock, MakeTuple, OpTag, OpType}; - use crate::{ops, type_row, types::FunctionType, Hugr, HugrView}; + use crate::{ops, type_row, types::Signature, Hugr, HugrView}; #[test] fn root_checked() { let root_type: OpType = ops::DFG { - signature: FunctionType::new(vec![], vec![]), + signature: Signature::new(vec![], vec![]), } .into(); let mut h = Hugr::new(root_type.clone()); diff --git a/hugr-core/src/hugr/views/sibling.rs b/hugr-core/src/hugr/views/sibling.rs index 5623b9330..1125bad25 100644 --- a/hugr-core/src/hugr/views/sibling.rs +++ b/hugr-core/src/hugr/views/sibling.rs @@ -385,7 +385,7 @@ mod test { use crate::ops::{dataflow::IOTrait, Input, OpTag, Output}; use crate::ops::{OpTrait, OpType}; use crate::type_row; - use crate::types::{FunctionType, Type}; + use crate::types::{Signature, Type}; use super::super::descendants::test::make_module_hgr; use super::*; @@ -409,7 +409,7 @@ mod test { #[test] fn nested_flat() -> Result<(), Box> { let mut module_builder = ModuleBuilder::new(); - let fty = FunctionType::new(type_row![NAT], type_row![NAT]); + let fty = Signature::new(type_row![NAT], type_row![NAT]); let mut fbuild = module_builder.define_function("main", fty.clone())?; let dfg = fbuild.dfg_builder(fty, fbuild.input_wires())?; let ins = dfg.input_wires(); diff --git a/hugr-core/src/hugr/views/sibling_subgraph.rs b/hugr-core/src/hugr/views/sibling_subgraph.rs index 07367e529..0757895ce 100644 --- a/hugr-core/src/hugr/views/sibling_subgraph.rs +++ b/hugr-core/src/hugr/views/sibling_subgraph.rs @@ -23,7 +23,7 @@ use crate::hugr::{HugrMut, HugrView, RootTagged}; use crate::ops::dataflow::DataflowOpTrait; use crate::ops::handle::{ContainerHandle, DataflowOpID}; use crate::ops::{NamedOp, OpTag, OpTrait, OpType}; -use crate::types::{FunctionType, Type}; +use crate::types::{Signature, Type}; use crate::{Hugr, IncomingPort, Node, OutgoingPort, Port, SimpleReplacement}; /// A non-empty convex subgraph of a HUGR sibling graph. @@ -285,7 +285,7 @@ impl SiblingSubgraph { } /// The signature of the subgraph. - pub fn signature(&self, hugr: &impl HugrView) -> FunctionType { + pub fn signature(&self, hugr: &impl HugrView) -> Signature { let input = self .inputs .iter() @@ -303,7 +303,7 @@ impl SiblingSubgraph { sig.port_type(p).cloned().expect("must be dataflow edge") }) .collect_vec(); - FunctionType::new(input, output).with_extension_delta(ExtensionSet::union_over( + Signature::new(input, output).with_extension_delta(ExtensionSet::union_over( self.nodes.iter().map(|n| { hugr.signature(*n) .expect("all nodes must have dataflow signature") @@ -666,9 +666,9 @@ pub enum InvalidReplacement { ] InvalidSignature { /// The expected signature. - expected: FunctionType, + expected: Signature, /// The actual signature. - actual: Option, + actual: Option, }, /// SiblingSubgraph is not convex. #[error("SiblingSubgraph is not convex.")] @@ -782,7 +782,7 @@ mod tests { let mut mod_builder = ModuleBuilder::new(); let func = mod_builder.declare( "test", - FunctionType::new_endo(type_row![QB_T, QB_T, QB_T]) + Signature::new_endo(type_row![QB_T, QB_T, QB_T]) .with_extension_delta(test_quantum_extension::EXTENSION_ID) .into(), )?; @@ -803,7 +803,7 @@ mod tests { let mut mod_builder = ModuleBuilder::new(); let func = mod_builder.declare( "test", - FunctionType::new_endo(type_row![BOOL_T]) + Signature::new_endo(type_row![BOOL_T]) .with_extension_delta(logic::EXTENSION_ID) .into(), )?; @@ -825,7 +825,7 @@ mod tests { let mut mod_builder = ModuleBuilder::new(); let func = mod_builder.declare( "test", - FunctionType::new(BOOL_T, type_row![BOOL_T, BOOL_T]) + Signature::new(BOOL_T, type_row![BOOL_T, BOOL_T]) .with_extension_delta(logic::EXTENSION_ID) .into(), )?; @@ -847,7 +847,7 @@ mod tests { let mut mod_builder = ModuleBuilder::new(); let func = mod_builder.declare( "test", - FunctionType::new_endo(BOOL_T) + Signature::new_endo(BOOL_T) .with_extension_delta(logic::EXTENSION_ID) .into(), )?; @@ -888,7 +888,7 @@ mod tests { let sub = SiblingSubgraph::try_new_dataflow_subgraph(&func)?; let empty_dfg = { - let builder = DFGBuilder::new(FunctionType::new_endo(type_row![QB_T, QB_T])).unwrap(); + let builder = DFGBuilder::new(Signature::new_endo(type_row![QB_T, QB_T])).unwrap(); let inputs = builder.input_wires(); builder.finish_prelude_hugr_with_outputs(inputs).unwrap() }; @@ -913,7 +913,7 @@ mod tests { // the first two qubits. assert_eq!( sub.signature(&func), - FunctionType::new_endo(type_row![QB_T, QB_T]) + Signature::new_endo(type_row![QB_T, QB_T]) .with_extension_delta(test_quantum_extension::EXTENSION_ID) ); Ok(()) @@ -926,7 +926,7 @@ mod tests { let sub = SiblingSubgraph::from_sibling_graph(&func)?; let empty_dfg = { - let builder = DFGBuilder::new(FunctionType::new_endo(type_row![QB_T])).unwrap(); + let builder = DFGBuilder::new(Signature::new_endo(type_row![QB_T])).unwrap(); let inputs = builder.input_wires(); builder.finish_prelude_hugr_with_outputs(inputs).unwrap() }; diff --git a/hugr-core/src/hugr/views/tests.rs b/hugr-core/src/hugr/views/tests.rs index 063e751d4..2762bff80 100644 --- a/hugr-core/src/hugr/views/tests.rs +++ b/hugr-core/src/hugr/views/tests.rs @@ -11,7 +11,7 @@ use crate::{ Value, }, type_row, - types::FunctionType, + types::Signature, utils::test_quantum_extension::cx_gate, Hugr, HugrView, }; @@ -176,7 +176,7 @@ fn test_dataflow_ports_only() { let local_and = dfg .define_function( "and", - FunctionType::new(type_row![BOOL_T; 2], type_row![BOOL_T]), + Signature::new(type_row![BOOL_T; 2], type_row![BOOL_T]), ) .unwrap(); let first_input = local_and.input().out_wire(0); diff --git a/hugr-core/src/macros.rs b/hugr-core/src/macros.rs index dea66c5bc..51483aadc 100644 --- a/hugr-core/src/macros.rs +++ b/hugr-core/src/macros.rs @@ -43,11 +43,11 @@ pub(crate) use impl_box_clone; /// Example: /// ``` /// # use hugr::type_row; -/// # use hugr::types::{FunctionType, Type, TypeRow}; +/// # use hugr::types::{Signature, Type, TypeRow}; /// const U: Type = Type::UNIT; /// let static_row: TypeRow = type_row![U, U]; /// let dynamic_row: TypeRow = vec![U, U, U].into(); -/// let sig = FunctionType::new(static_row, dynamic_row); +/// let sig = Signature::new(static_row, dynamic_row); /// /// let repeated_row: TypeRow = type_row![U; 3]; /// assert_eq!(repeated_row, *sig.output()); diff --git a/hugr-core/src/ops.rs b/hugr-core/src/ops.rs index f44bfd136..1a2b000f6 100644 --- a/hugr-core/src/ops.rs +++ b/hugr-core/src/ops.rs @@ -10,7 +10,7 @@ pub mod module; pub mod tag; pub mod validate; use crate::extension::ExtensionSet; -use crate::types::{EdgeKind, FunctionType}; +use crate::types::{EdgeKind, Signature}; use crate::{Direction, OutgoingPort, Port}; use crate::{IncomingPort, PortIndex}; use paste::paste; @@ -343,7 +343,7 @@ pub trait OpTrait { /// The signature of the operation. /// /// Only dataflow operations have a signature, otherwise returns None. - fn dataflow_signature(&self) -> Option { + fn dataflow_signature(&self) -> Option { None } @@ -406,13 +406,13 @@ pub trait OpParent { /// sibling graph. /// /// Non-container ops like `FuncDecl` return `None` even though they represent a function. - fn inner_function_type(&self) -> Option { + fn inner_function_type(&self) -> Option { None } } impl OpParent for T { - fn inner_function_type(&self) -> Option { + fn inner_function_type(&self) -> Option { Some(DataflowParent::inner_signature(self)) } } diff --git a/hugr-core/src/ops/constant.rs b/hugr-core/src/ops/constant.rs index 4fc3e116f..04b8d77cc 100644 --- a/hugr-core/src/ops/constant.rs +++ b/hugr-core/src/ops/constant.rs @@ -5,7 +5,7 @@ mod custom; use super::{NamedOp, OpName, OpTrait, StaticTag}; use super::{OpTag, OpType}; use crate::extension::ExtensionSet; -use crate::types::{CustomType, EdgeKind, FunctionType, SumType, SumTypeError, Type}; +use crate::types::{CustomType, EdgeKind, Signature, SumType, SumTypeError, Type}; use crate::{Hugr, HugrView}; use delegate::delegate; @@ -327,7 +327,7 @@ pub enum ConstTypeError { } /// Hugrs (even functions) inside Consts must be monomorphic -fn mono_fn_type(h: &Hugr) -> Result { +fn mono_fn_type(h: &Hugr) -> Result { let err = || ConstTypeError::NotMonomorphicFunction { hugr_root_type: h.root_type().clone(), }; @@ -604,7 +604,7 @@ mod test { let w = b.load_const(&c); b.finish_hugr_with_outputs([w], &test_registry()).unwrap(); - let mut b = DFGBuilder::new(FunctionType::new( + let mut b = DFGBuilder::new(Signature::new( type_row![], TypeRow::from(vec![pred_ty.clone().into()]), ))?; @@ -661,7 +661,7 @@ mod test { fn function_value(simple_dfg_hugr: Hugr) { let v = Value::function(simple_dfg_hugr).unwrap(); - let correct_type = Type::new_function(FunctionType::new_endo(type_row![ + let correct_type = Type::new_function(Signature::new_endo(type_row![ crate::extension::prelude::BOOL_T ])); diff --git a/hugr-core/src/ops/controlflow.rs b/hugr-core/src/ops/controlflow.rs index b1a6b0e37..ad60e7b86 100644 --- a/hugr-core/src/ops/controlflow.rs +++ b/hugr-core/src/ops/controlflow.rs @@ -1,7 +1,7 @@ //! Control flow operations. use crate::extension::ExtensionSet; -use crate::types::{EdgeKind, FunctionType, Type, TypeRow}; +use crate::types::{EdgeKind, Signature, Type, TypeRow}; use crate::Direction; use super::dataflow::{DataflowOpTrait, DataflowParent}; @@ -31,10 +31,10 @@ impl DataflowOpTrait for TailLoop { "A tail-controlled loop" } - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { let [inputs, outputs] = [&self.just_inputs, &self.just_outputs].map(|row| row.extend(self.rest.iter())); - FunctionType::new(inputs, outputs).with_extension_delta(self.extension_delta.clone()) + Signature::new(inputs, outputs).with_extension_delta(self.extension_delta.clone()) } } @@ -54,8 +54,8 @@ impl TailLoop { } impl DataflowParent for TailLoop { - fn inner_signature(&self) -> FunctionType { - FunctionType::new(self.body_input_row(), self.body_output_row()) + fn inner_signature(&self) -> Signature { + Signature::new(self.body_input_row(), self.body_output_row()) .with_extension_delta(self.extension_delta.clone()) } } @@ -82,12 +82,12 @@ impl DataflowOpTrait for Conditional { "HUGR conditional operation" } - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { let mut inputs = self.other_inputs.clone(); inputs .to_mut() .insert(0, Type::new_sum(self.sum_rows.clone())); - FunctionType::new(inputs, self.outputs.clone()) + Signature::new(inputs, self.outputs.clone()) .with_extension_delta(self.extension_delta.clone()) } } @@ -104,7 +104,7 @@ impl Conditional { #[allow(missing_docs)] #[cfg_attr(test, derive(proptest_derive::Arbitrary))] pub struct CFG { - pub signature: FunctionType, + pub signature: Signature, } impl_op_name!(CFG); @@ -116,7 +116,7 @@ impl DataflowOpTrait for CFG { "A dataflow node defined by a child CFG" } - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { self.signature.clone() } } @@ -162,12 +162,12 @@ impl StaticTag for ExitBlock { } impl DataflowParent for DataflowBlock { - fn inner_signature(&self) -> FunctionType { + fn inner_signature(&self) -> Signature { // The node outputs a Sum before the data outputs of the block node let sum_type = Type::new_sum(self.sum_rows.clone()); let mut node_outputs = vec![sum_type]; node_outputs.extend_from_slice(&self.other_outputs); - FunctionType::new(self.inputs.clone(), TypeRow::from(node_outputs)) + Signature::new(self.inputs.clone(), TypeRow::from(node_outputs)) .with_extension_delta(self.extension_delta.clone()) } } @@ -260,7 +260,7 @@ impl BasicBlock for ExitBlock { /// Case ops - nodes valid inside Conditional nodes. pub struct Case { /// The signature of the contained dataflow graph. - pub signature: FunctionType, + pub signature: Signature, } impl_op_name!(Case); @@ -270,7 +270,7 @@ impl StaticTag for Case { } impl DataflowParent for Case { - fn inner_signature(&self) -> FunctionType { + fn inner_signature(&self) -> Signature { self.signature.clone() } } diff --git a/hugr-core/src/ops/custom.rs b/hugr-core/src/ops/custom.rs index 8f4e3f19c..cfbcfc145 100644 --- a/hugr-core/src/ops/custom.rs +++ b/hugr-core/src/ops/custom.rs @@ -14,7 +14,7 @@ use crate::extension::{ConstFoldResult, ExtensionId, ExtensionRegistry, OpDef, S use crate::hugr::internal::HugrMutInternals; use crate::hugr::HugrView; use crate::types::EdgeKind; -use crate::types::{type_param::TypeArg, FunctionType}; +use crate::types::{type_param::TypeArg, Signature}; use crate::{ops, Hugr, IncomingPort, Node}; use super::dataflow::DataflowOpTrait; @@ -132,7 +132,7 @@ impl DataflowOpTrait for CustomOp { } /// The signature of the operation. - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { match self { Self::Opaque(op) => op.signature.clone(), Self::Extension(ext_op) => ext_op.signature(), @@ -181,7 +181,7 @@ pub struct ExtensionOp { )] def: Arc, args: Vec, - signature: FunctionType, // Cache + signature: Signature, // Cache } impl ExtensionOp { @@ -271,7 +271,7 @@ impl DataflowOpTrait for ExtensionOp { self.def().description() } - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { self.signature.clone() } } @@ -286,7 +286,7 @@ pub struct OpaqueOp { #[cfg_attr(test, proptest(strategy = "any_nonempty_string()"))] description: String, // cache in advance so description() can return &str args: Vec, - signature: FunctionType, + signature: Signature, } fn qualify_name(res_id: &ExtensionId, op_name: &OpNameRef) -> OpName { @@ -300,7 +300,7 @@ impl OpaqueOp { op_name: impl Into, description: String, args: impl Into>, - signature: FunctionType, + signature: Signature, ) -> Self { Self { extension, @@ -342,7 +342,7 @@ impl DataflowOpTrait for OpaqueOp { &self.description } - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { self.signature.clone() } } @@ -422,8 +422,8 @@ pub enum CustomOpError { SignatureMismatch { extension: ExtensionId, op: OpName, - stored: FunctionType, - computed: FunctionType, + stored: Signature, + computed: Signature, }, } @@ -435,7 +435,7 @@ mod test { #[test] fn new_opaque_op() { - let sig = FunctionType::new_endo(vec![QB_T]); + let sig = Signature::new_endo(vec![QB_T]); let op: CustomOp = OpaqueOp::new( "res".try_into().unwrap(), "op", diff --git a/hugr-core/src/ops/dataflow.rs b/hugr-core/src/ops/dataflow.rs index 0e6dc1800..364429784 100644 --- a/hugr-core/src/ops/dataflow.rs +++ b/hugr-core/src/ops/dataflow.rs @@ -4,7 +4,7 @@ use super::{impl_op_name, OpTag, OpTrait}; use crate::extension::{ExtensionRegistry, ExtensionSet, SignatureError}; use crate::ops::StaticTag; -use crate::types::{EdgeKind, FunctionType, PolyFuncType, Type, TypeArg, TypeRow}; +use crate::types::{EdgeKind, PolyFuncType, Signature, Type, TypeArg, TypeRow}; use crate::IncomingPort; #[cfg(test)] @@ -19,7 +19,7 @@ pub trait DataflowOpTrait { fn description(&self) -> &str; /// The signature of the operation. - fn signature(&self) -> FunctionType; + fn signature(&self) -> Signature; /// The edge kind for the non-dataflow or constant inputs of the operation, /// not described by the signature. @@ -105,8 +105,8 @@ impl DataflowOpTrait for Input { None } - fn signature(&self) -> FunctionType { - FunctionType::new(TypeRow::new(), self.types.clone()) + fn signature(&self) -> Signature { + Signature::new(TypeRow::new(), self.types.clone()) } } impl DataflowOpTrait for Output { @@ -118,8 +118,8 @@ impl DataflowOpTrait for Output { // Note: We know what the input extensions should be, so we *could* give an // instantiated Signature instead - fn signature(&self) -> FunctionType { - FunctionType::new(self.types.clone(), TypeRow::new()) + fn signature(&self) -> Signature { + Signature::new(self.types.clone(), TypeRow::new()) } fn other_output(&self) -> Option { @@ -134,7 +134,7 @@ impl OpTrait for T { fn tag(&self) -> OpTag { T::TAG } - fn dataflow_signature(&self) -> Option { + fn dataflow_signature(&self) -> Option { Some(DataflowOpTrait::signature(self)) } fn extension_delta(&self) -> ExtensionSet { @@ -169,7 +169,7 @@ pub struct Call { /// The type arguments that instantiate `func_sig`. pub type_args: Vec, /// The instantiation of `func_sig`. - pub instantiation: FunctionType, // Cache, so we can fail in try_new() not in signature() + pub instantiation: Signature, // Cache, so we can fail in try_new() not in signature() } impl_op_name!(Call); @@ -180,7 +180,7 @@ impl DataflowOpTrait for Call { "Call a function directly" } - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { self.instantiation.clone() } @@ -220,10 +220,10 @@ impl Call { /// ``` /// # use hugr::ops::dataflow::Call; /// # use hugr::ops::OpType; - /// # use hugr::types::FunctionType; + /// # use hugr::types::Signature; /// # use hugr::extension::prelude::QB_T; /// # use hugr::extension::PRELUDE_REGISTRY; - /// let signature = FunctionType::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())); @@ -261,7 +261,7 @@ impl Call { #[cfg_attr(test, derive(Arbitrary))] pub struct CallIndirect { /// Signature of function being called - pub signature: FunctionType, + pub signature: Signature, } impl_op_name!(CallIndirect); @@ -272,7 +272,7 @@ impl DataflowOpTrait for CallIndirect { "Call a function indirectly" } - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { let mut s = self.signature.clone(); s.input .to_mut() @@ -296,8 +296,8 @@ impl DataflowOpTrait for LoadConstant { "Load a static constant in to the local dataflow graph" } - fn signature(&self) -> FunctionType { - FunctionType::new(TypeRow::new(), vec![self.datatype.clone()]) + fn signature(&self) -> Signature { + Signature::new(TypeRow::new(), vec![self.datatype.clone()]) } fn static_input(&self) -> Option { @@ -341,7 +341,7 @@ pub struct LoadFunction { /// The type arguments that instantiate `func_sig`. pub type_args: Vec, /// The instantiation of `func_sig`. - pub signature: FunctionType, // Cache, so we can fail in try_new() not in signature() + pub signature: Signature, // Cache, so we can fail in try_new() not in signature() } impl_op_name!(LoadFunction); impl DataflowOpTrait for LoadFunction { @@ -351,7 +351,7 @@ impl DataflowOpTrait for LoadFunction { "Load a static function in to the local dataflow graph" } - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { self.signature.clone() } @@ -371,7 +371,7 @@ impl LoadFunction { ) -> Result { let type_args = type_args.into(); let instantiation = func_sig.instantiate(&type_args, exts)?; - let signature = FunctionType::new(TypeRow::new(), vec![Type::new_function(instantiation)]); + let signature = Signature::new(TypeRow::new(), vec![Type::new_function(instantiation)]); Ok(Self { func_sig, type_args, @@ -418,7 +418,7 @@ impl LoadFunction { /// Operations that is the parent of a dataflow graph. pub trait DataflowParent { /// Signature of the inner dataflow graph. - fn inner_signature(&self) -> FunctionType; + fn inner_signature(&self) -> Signature; } /// A simply nested dataflow graph. @@ -426,13 +426,13 @@ pub trait DataflowParent { #[cfg_attr(test, derive(Arbitrary))] pub struct DFG { /// Signature of DFG node - pub signature: FunctionType, + pub signature: Signature, } impl_op_name!(DFG); impl DataflowParent for DFG { - fn inner_signature(&self) -> FunctionType { + fn inner_signature(&self) -> Signature { self.signature.clone() } } @@ -444,7 +444,7 @@ impl DataflowOpTrait for DFG { "A simply nested dataflow graph" } - fn signature(&self) -> FunctionType { + fn signature(&self) -> Signature { self.inner_signature() } } diff --git a/hugr-core/src/ops/leaf.rs b/hugr-core/src/ops/leaf.rs index 0e345669f..ab6171901 100644 --- a/hugr-core/src/ops/leaf.rs +++ b/hugr-core/src/ops/leaf.rs @@ -7,7 +7,7 @@ use crate::extension::ExtensionSet; use crate::{ extension::ExtensionId, - types::{EdgeKind, FunctionType, Type, TypeRow}, + types::{EdgeKind, Signature, Type, TypeRow}, }; /// A no-op operation. @@ -121,8 +121,8 @@ impl DataflowOpTrait for Noop { } /// The signature of the operation. - fn signature(&self) -> FunctionType { - FunctionType::new(vec![self.ty.clone()], vec![self.ty.clone()]) + fn signature(&self) -> Signature { + Signature::new(vec![self.ty.clone()], vec![self.ty.clone()]) } fn other_input(&self) -> Option { @@ -143,8 +143,8 @@ impl DataflowOpTrait for MakeTuple { } /// The signature of the operation. - fn signature(&self) -> FunctionType { - FunctionType::new(self.tys.clone(), vec![Type::new_tuple(self.tys.clone())]) + fn signature(&self) -> Signature { + Signature::new(self.tys.clone(), vec![Type::new_tuple(self.tys.clone())]) } fn other_input(&self) -> Option { @@ -165,8 +165,8 @@ impl DataflowOpTrait for UnpackTuple { } /// The signature of the operation. - fn signature(&self) -> FunctionType { - FunctionType::new(vec![Type::new_tuple(self.tys.clone())], self.tys.clone()) + fn signature(&self) -> Signature { + Signature::new(vec![Type::new_tuple(self.tys.clone())], self.tys.clone()) } fn other_input(&self) -> Option { @@ -187,8 +187,8 @@ impl DataflowOpTrait for Tag { } /// The signature of the operation. - fn signature(&self) -> FunctionType { - FunctionType::new( + fn signature(&self) -> Signature { + Signature::new( self.variants .get(self.tag) .expect("Not a valid tag") @@ -215,8 +215,8 @@ impl DataflowOpTrait for Lift { } /// The signature of the operation. - fn signature(&self) -> FunctionType { - FunctionType::new(self.type_row.clone(), self.type_row.clone()) + fn signature(&self) -> Signature { + Signature::new(self.type_row.clone(), self.type_row.clone()) .with_extension_delta(ExtensionSet::singleton(&self.new_extension)) } diff --git a/hugr-core/src/ops/module.rs b/hugr-core/src/ops/module.rs index ea4e67744..cb10d4c2f 100644 --- a/hugr-core/src/ops/module.rs +++ b/hugr-core/src/ops/module.rs @@ -7,7 +7,7 @@ use { ::proptest_derive::Arbitrary, }; -use crate::types::{EdgeKind, FunctionType, PolyFuncType}; +use crate::types::{EdgeKind, PolyFuncType, Signature}; use crate::types::{Type, TypeBound}; use super::dataflow::DataflowParent; @@ -64,7 +64,7 @@ impl StaticTag for FuncDefn { } impl DataflowParent for FuncDefn { - fn inner_signature(&self) -> FunctionType { + fn inner_signature(&self) -> Signature { self.signature.body().clone() } } diff --git a/hugr-core/src/std_extensions/arithmetic/float_ops.rs b/hugr-core/src/std_extensions/arithmetic/float_ops.rs index b098d89dd..f701da233 100644 --- a/hugr-core/src/std_extensions/arithmetic/float_ops.rs +++ b/hugr-core/src/std_extensions/arithmetic/float_ops.rs @@ -10,7 +10,7 @@ use crate::{ ExtensionId, ExtensionRegistry, ExtensionSet, OpDef, SignatureFunc, PRELUDE, }, type_row, - types::FunctionType, + types::Signature, Extension, }; use lazy_static::lazy_static; @@ -56,13 +56,13 @@ impl MakeOpDef for FloatOps { match self { feq | fne | flt | fgt | fle | fge => { - FunctionType::new(type_row![FLOAT64_TYPE; 2], type_row![BOOL_T]) + Signature::new(type_row![FLOAT64_TYPE; 2], type_row![BOOL_T]) } fmax | fmin | fadd | fsub | fmul | fdiv => { - FunctionType::new(type_row![FLOAT64_TYPE; 2], type_row![FLOAT64_TYPE]) + Signature::new(type_row![FLOAT64_TYPE; 2], type_row![FLOAT64_TYPE]) } - fneg | fabs | ffloor | fceil => FunctionType::new_endo(type_row![FLOAT64_TYPE]), - ftostring => FunctionType::new(type_row![FLOAT64_TYPE], STRING_TYPE), + fneg | fabs | ffloor | fceil => Signature::new_endo(type_row![FLOAT64_TYPE]), + ftostring => Signature::new(type_row![FLOAT64_TYPE], STRING_TYPE), } .into() } diff --git a/hugr-core/src/std_extensions/arithmetic/int_ops.rs b/hugr-core/src/std_extensions/arithmetic/int_ops.rs index 88290f56e..d7f539682 100644 --- a/hugr-core/src/std_extensions/arithmetic/int_ops.rs +++ b/hugr-core/src/std_extensions/arithmetic/int_ops.rs @@ -356,7 +356,7 @@ fn sum_ty_with_err(t: Type) -> Type { mod test { use crate::{ ops::dataflow::DataflowOpTrait, std_extensions::arithmetic::int_types::int_type, - types::FunctionType, + types::Signature, }; use super::*; @@ -379,7 +379,7 @@ mod test { .to_extension_op() .unwrap() .signature(), - FunctionType::new(int_type(3), int_type(4)).with_extension_delta(EXTENSION_ID) + Signature::new(int_type(3), int_type(4)).with_extension_delta(EXTENSION_ID) ); assert_eq!( IntOpDef::iwiden_s @@ -387,7 +387,7 @@ mod test { .to_extension_op() .unwrap() .signature(), - FunctionType::new_endo(int_type(3)).with_extension_delta(EXTENSION_ID) + Signature::new_endo(int_type(3)).with_extension_delta(EXTENSION_ID) ); assert_eq!( IntOpDef::inarrow_s @@ -395,7 +395,7 @@ mod test { .to_extension_op() .unwrap() .signature(), - FunctionType::new(int_type(3), sum_ty_with_err(int_type(3))) + Signature::new(int_type(3), sum_ty_with_err(int_type(3))) .with_extension_delta(EXTENSION_ID) ); assert!( @@ -412,7 +412,7 @@ mod test { .to_extension_op() .unwrap() .signature(), - FunctionType::new(int_type(2), sum_ty_with_err(int_type(1))) + Signature::new(int_type(2), sum_ty_with_err(int_type(1))) .with_extension_delta(EXTENSION_ID) ); diff --git a/hugr-core/src/std_extensions/logic.rs b/hugr-core/src/std_extensions/logic.rs index e571d745d..cb5454285 100644 --- a/hugr-core/src/std_extensions/logic.rs +++ b/hugr-core/src/std_extensions/logic.rs @@ -5,7 +5,7 @@ use strum_macros::{EnumIter, EnumString, IntoStaticStr}; use crate::extension::{ConstFold, ConstFoldResult}; use crate::ops::constant::ValueName; use crate::ops::{OpName, Value}; -use crate::types::{FuncValueType, FunctionType}; +use crate::types::{FuncValueType, Signature}; use crate::{ extension::{ prelude::BOOL_T, @@ -134,7 +134,7 @@ impl MakeOpDef for NotOp { } fn signature(&self) -> SignatureFunc { - FunctionType::new_endo(type_row![BOOL_T]).into() + Signature::new_endo(type_row![BOOL_T]).into() } fn description(&self) -> String { "logical 'not'".into() diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index 58c3b57ec..9747fd0e0 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -17,7 +17,7 @@ use crate::utils::display_list_with_separator; pub use check::SumTypeError; pub use custom::CustomType; pub use poly_func::{PolyFuncType, PolyFuncTypeRV}; -pub use signature::{FuncValueType, FunctionType}; +pub use signature::{FuncValueType, Signature}; use smol_str::SmolStr; pub use type_param::TypeArg; pub use type_row::{TypeRow, TypeRowRV}; @@ -278,9 +278,9 @@ impl TypeEnum { /// ``` /// /// ``` -/// # use hugr::types::{Type, TypeBound, FunctionType}; +/// # use hugr::types::{Type, TypeBound, Signature}; /// -/// let func_type: Type = Type::new_function(FunctionType::new_endo(vec![])); +/// let func_type: Type = Type::new_function(Signature::new_endo(vec![])); /// assert_eq!(func_type.least_upper_bound(), TypeBound::Copyable); /// ``` pub struct TypeBase(TypeEnum, TypeBound); @@ -605,7 +605,7 @@ pub(crate) mod test { fn construct() { let t: Type = Type::new_tuple(vec![ USIZE_T, - Type::new_function(FunctionType::new_endo(vec![])), + Type::new_function(Signature::new_endo(vec![])), Type::new_extension(CustomType::new( "my_custom", [], diff --git a/hugr-core/src/types/poly_func.rs b/hugr-core/src/types/poly_func.rs index 3368034b6..70c60ed28 100644 --- a/hugr-core/src/types/poly_func.rs +++ b/hugr-core/src/types/poly_func.rs @@ -155,7 +155,7 @@ pub(crate) mod test { use crate::types::signature::FuncTypeBase; use crate::types::type_param::{TypeArg, TypeArgError, TypeParam}; use crate::types::{ - CustomType, FuncValueType, FunctionType, MaybeRV, Type, TypeBound, TypeName, TypeRV, + CustomType, FuncValueType, MaybeRV, Signature, Type, TypeBound, TypeName, TypeRV, }; use crate::Extension; @@ -185,14 +185,14 @@ 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()], - FunctionType::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)?; assert_eq!( t, - FunctionType::new( + Signature::new( vec![Type::new_extension( list_def .instantiate([TypeArg::Type { ty: USIZE_T }]) @@ -216,7 +216,7 @@ pub(crate) mod test { let good_array = Type::new_extension(ar_def.instantiate([tyvar.clone(), szvar.clone()])?); let good_ts = PolyFuncTypeBase::new_validated( typarams.clone(), - FunctionType::new_endo(good_array), + Signature::new_endo(good_array), &PRELUDE_REGISTRY, )?; @@ -258,7 +258,7 @@ pub(crate) mod test { )); let bad_ts = PolyFuncTypeBase::new_validated( typarams.clone(), - FunctionType::new_endo(bad_array), + Signature::new_endo(bad_array), &PRELUDE_REGISTRY, ); assert_eq!(bad_ts.err(), Some(arg_err)); @@ -271,7 +271,7 @@ pub(crate) mod test { // Variables in args have different bounds from variable declaration let tv = TypeArg::new_var_use(0, TypeBound::Copyable.into()); let list_def = EXTENSION.get_type(&LIST_TYPENAME).unwrap(); - let body_type = FunctionType::new_endo(Type::new_extension(list_def.instantiate([tv])?)); + let body_type = Signature::new_endo(Type::new_extension(list_def.instantiate([tv])?)); for decl in [ TypeParam::Extensions, TypeParam::List { @@ -327,7 +327,7 @@ pub(crate) mod test { let make_scheme = |tp: TypeParam| { PolyFuncTypeBase::new_validated( [tp.clone()], - FunctionType::new_endo(Type::new_extension(CustomType::new( + Signature::new_endo(Type::new_extension(CustomType::new( TYPE_NAME, [TypeArg::new_var_use(0, tp)], EXT_ID, @@ -406,7 +406,7 @@ pub(crate) mod test { // Declared as row variable, used as type variable let e = PolyFuncTypeBase::new_validated( [decl.clone()], - FunctionType::new_endo(vec![Type::new_var_use(0, TypeBound::Any)]), + Signature::new_endo(vec![Type::new_var_use(0, TypeBound::Any)]), &EMPTY_REG, ) .unwrap_err(); @@ -447,7 +447,7 @@ pub(crate) mod test { .unwrap(); assert_eq!( t2, - FunctionType::new( + Signature::new( vec![USIZE_T, USIZE_T, BOOL_T], vec![Type::new_tuple(vec![USIZE_T, BOOL_T])] ) @@ -466,12 +466,12 @@ pub(crate) mod test { b: TypeBound::Copyable, }), }], - FunctionType::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(FunctionType::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 { @@ -482,7 +482,7 @@ pub(crate) mod test { .unwrap(); assert_eq!( t3, - FunctionType::new(vec![USIZE_T, inner3.clone()], vec![inner3]) + Signature::new(vec![USIZE_T, inner3.clone()], vec![inner3]) ); } } diff --git a/hugr-core/src/types/signature.rs b/hugr-core/src/types/signature.rs index 81fea1be2..74621be37 100644 --- a/hugr-core/src/types/signature.rs +++ b/hugr-core/src/types/signature.rs @@ -39,7 +39,7 @@ pub struct FuncTypeBase { /// or within a [FuncDefn], also the target (value) of a call (static). /// /// [FuncDefn]: crate::ops::FuncDefn -pub type FunctionType = FuncTypeBase; +pub type Signature = FuncTypeBase; /// A function that may contain [RowVariable]s and thus has potentially-unknown arity; /// used for [OpDef]'s and passable as a value round a Hugr (see [Type::new_function]) @@ -130,7 +130,7 @@ impl Default for FuncTypeBase { } } -impl FunctionType { +impl Signature { /// Returns the type of a value [`Port`]. Returns `None` if the port is out /// of bounds. #[inline] @@ -257,7 +257,7 @@ impl Display for FuncTypeBase { } } -impl TryFrom for FunctionType { +impl TryFrom for Signature { type Error = SignatureError; fn try_from(value: FuncValueType) -> Result { @@ -267,8 +267,8 @@ impl TryFrom for FunctionType { } } -impl From for FuncValueType { - fn from(value: FunctionType) -> Self { +impl From for FuncValueType { + fn from(value: Signature) -> Self { Self { input: value.input.into(), output: value.output.into(), @@ -292,7 +292,7 @@ mod test { use super::*; #[test] fn test_function_type() { - let mut f_type = FunctionType::new(type_row![Type::UNIT], type_row![Type::UNIT]); + let mut f_type = Signature::new(type_row![Type::UNIT], type_row![Type::UNIT]); assert_eq!(f_type.input_count(), 1); assert_eq!(f_type.output_count(), 1); diff --git a/hugr-core/src/utils.rs b/hugr-core/src/utils.rs index 91aeb046e..3693743ea 100644 --- a/hugr-core/src/utils.rs +++ b/hugr-core/src/utils.rs @@ -112,7 +112,7 @@ pub(crate) mod test_quantum_extension { ops::CustomOp, std_extensions::arithmetic::float_types, type_row, - types::{FunctionType, PolyFuncTypeRV}, + types::{PolyFuncTypeRV, Signature}, Extension, }; @@ -137,7 +137,7 @@ pub(crate) mod test_quantum_extension { .add_op( OpName::new_inline("RzF64"), "Rotation specified by float".into(), - FunctionType::new(type_row![QB_T, float_types::FLOAT64_TYPE], type_row![QB_T]), + Signature::new(type_row![QB_T, float_types::FLOAT64_TYPE], type_row![QB_T]), ) .unwrap(); @@ -149,7 +149,7 @@ pub(crate) mod test_quantum_extension { .add_op( OpName::new_inline("Measure"), "Measure a qubit, returning the qubit and the measurement result.".into(), - FunctionType::new(type_row![QB_T], type_row![QB_T, BOOL_T]), + Signature::new(type_row![QB_T], type_row![QB_T, BOOL_T]), ) .unwrap(); @@ -157,7 +157,7 @@ pub(crate) mod test_quantum_extension { .add_op( OpName::new_inline("QAlloc"), "Allocate a new qubit.".into(), - FunctionType::new(type_row![], type_row![QB_T]), + Signature::new(type_row![], type_row![QB_T]), ) .unwrap(); @@ -165,7 +165,7 @@ pub(crate) mod test_quantum_extension { .add_op( OpName::new_inline("QDiscard"), "Discard a qubit.".into(), - FunctionType::new(type_row![QB_T], type_row![]), + Signature::new(type_row![QB_T], type_row![]), ) .unwrap(); diff --git a/hugr-passes/src/const_fold/test.rs b/hugr-passes/src/const_fold/test.rs index 437253281..768bcffc7 100644 --- a/hugr-passes/src/const_fold/test.rs +++ b/hugr-passes/src/const_fold/test.rs @@ -8,7 +8,7 @@ use hugr_core::std_extensions::arithmetic::int_ops::IntOpDef; use hugr_core::std_extensions::arithmetic::int_types::{ConstInt, INT_TYPES}; use hugr_core::std_extensions::logic::{self, NaryLogic, NotOp}; use hugr_core::type_row; -use hugr_core::types::{FunctionType, Type, TypeRow, TypeRowRV}; +use hugr_core::types::{Signature, Type, TypeRow, TypeRowRV}; use rstest::rstest; @@ -73,7 +73,7 @@ fn test_add(#[case] a: f64, #[case] b: f64, #[case] c: f64) { assert_eq!(outs.as_slice(), &[(0.into(), c)]); } -fn noargfn(outputs: impl Into) -> FunctionType { +fn noargfn(outputs: impl Into) -> Signature { inout_ft(type_row![], outputs) } @@ -137,11 +137,8 @@ fn test_list_ops() -> Result<(), Box> { ]) .unwrap(); let list: Value = ListValue::new(BOOL_T, [Value::false_val()]).into(); - let mut build = DFGBuilder::new(FunctionType::new( - type_row![], - vec![list.get_type().clone()], - )) - .unwrap(); + let mut build = + DFGBuilder::new(Signature::new(type_row![], vec![list.get_type().clone()])).unwrap(); let list_wire = build.add_load_const(list.clone()); diff --git a/hugr-passes/src/force_order.rs b/hugr-passes/src/force_order.rs index c2f7b9221..91e309786 100644 --- a/hugr-passes/src/force_order.rs +++ b/hugr-passes/src/force_order.rs @@ -211,7 +211,7 @@ mod test { use hugr_core::ops::Value; use hugr_core::std_extensions::arithmetic::int_ops::{self, IntOpDef}; use hugr_core::std_extensions::arithmetic::int_types::INT_TYPES; - use hugr_core::types::{FunctionType, Type}; + use hugr_core::types::{Signature, Type}; use hugr_core::{builder::DFGBuilder, hugr::Hugr}; use hugr_core::{HugrView, Wire}; @@ -324,7 +324,7 @@ mod test { fn test_force_order_const() { let mut hugr = { let mut builder = - DFGBuilder::new(FunctionType::new(Type::EMPTY_TYPEROW, Type::UNIT)).unwrap(); + DFGBuilder::new(Signature::new(Type::EMPTY_TYPEROW, Type::UNIT)).unwrap(); let unit = builder.add_load_value(Value::unary_unit_sum()); builder .finish_hugr_with_outputs([unit], &EMPTY_REG) diff --git a/hugr-passes/src/merge_bbs.rs b/hugr-passes/src/merge_bbs.rs index c1e8b7b23..aaac004ad 100644 --- a/hugr-passes/src/merge_bbs.rs +++ b/hugr-passes/src/merge_bbs.rs @@ -168,7 +168,7 @@ mod test { use hugr_core::ops::constant::Value; use hugr_core::ops::handle::CfgID; use hugr_core::ops::{Lift, LoadConstant, Noop, OpTrait, OpType}; - use hugr_core::types::{FunctionType, Type, TypeRow}; + use hugr_core::types::{Signature, Type, TypeRow}; use hugr_core::{const_extension_ids, type_row, Extension, Hugr, HugrView, Wire}; use super::merge_basic_blocks; @@ -182,7 +182,7 @@ mod test { e.add_op( "Test".into(), String::new(), - FunctionType::new( + Signature::new( type_row![QB_T, USIZE_T], TypeRow::from(vec![Type::new_sum(vec![ type_row![QB_T], diff --git a/hugr-passes/src/nest_cfgs.rs b/hugr-passes/src/nest_cfgs.rs index 08b857b1f..32d207844 100644 --- a/hugr-passes/src/nest_cfgs.rs +++ b/hugr-passes/src/nest_cfgs.rs @@ -585,7 +585,7 @@ pub(crate) mod test { use hugr_core::ops::handle::{ConstID, NodeHandle}; use hugr_core::ops::Value; use hugr_core::type_row; - use hugr_core::types::{EdgeKind, FunctionType, Type}; + use hugr_core::types::{EdgeKind, Signature, Type}; use hugr_core::utils::depth; const NAT: Type = USIZE_T; @@ -608,7 +608,7 @@ pub(crate) mod test { // /-> left --\ // entry -> split > merge -> head -> tail -> exit // \-> right -/ \-<--<-/ - let mut cfg_builder = CFGBuilder::new(FunctionType::new_endo(NAT))?; + let mut cfg_builder = CFGBuilder::new(Signature::new_endo(NAT))?; 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()); @@ -876,7 +876,7 @@ 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(FunctionType::new_endo(NAT))?; + let mut cfg_builder = CFGBuilder::new(Signature::new_endo(NAT))?; 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()); @@ -903,7 +903,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(FunctionType::new_endo(NAT))?; + let mut cfg_builder = CFGBuilder::new(Signature::new_endo(NAT))?; let (head, tail) = build_conditional_in_loop(&mut cfg_builder, separate_headers)?; let h = cfg_builder.finish_prelude_hugr()?; Ok((h, head, tail)) diff --git a/hugr/benches/benchmarks/hugr.rs b/hugr/benches/benchmarks/hugr.rs index eb7fe60de..ee28742c3 100644 --- a/hugr/benches/benchmarks/hugr.rs +++ b/hugr/benches/benchmarks/hugr.rs @@ -3,12 +3,12 @@ use criterion::{black_box, criterion_group, AxisScale, Criterion, PlotConfiguration}; use hugr::builder::{BuildError, CFGBuilder, DFGBuilder, Dataflow, DataflowHugr, HugrBuilder}; use hugr::extension::prelude::{BOOL_T, USIZE_T}; -use hugr::types::FunctionType; +use hugr::types::Signature; use hugr::{type_row, Hugr}; pub fn simple_dfg_hugr() -> Hugr { let dfg_builder = - DFGBuilder::new(FunctionType::new(type_row![BOOL_T], type_row![BOOL_T])).unwrap(); + DFGBuilder::new(Signature::new(type_row![BOOL_T], type_row![BOOL_T])).unwrap(); let [i1] = dfg_builder.input_wires_arr(); dfg_builder.finish_prelude_hugr_with_outputs([i1]).unwrap() } @@ -25,7 +25,7 @@ pub fn simple_cfg_builder + AsRef>( entry_b.finish_with_outputs(sum, [])? }; let mut middle_b = cfg_builder - .simple_block_builder(FunctionType::new(type_row![USIZE_T], type_row![USIZE_T]), 1)?; + .simple_block_builder(Signature::new(type_row![USIZE_T], type_row![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(); @@ -40,7 +40,7 @@ pub fn simple_cfg_builder + AsRef>( pub fn simple_cfg_hugr() -> Hugr { let mut cfg_builder = - CFGBuilder::new(FunctionType::new(type_row![USIZE_T], type_row![USIZE_T])).unwrap(); + CFGBuilder::new(Signature::new(type_row![USIZE_T], type_row![USIZE_T])).unwrap(); simple_cfg_builder(&mut cfg_builder).unwrap(); cfg_builder.finish_prelude_hugr().unwrap() } diff --git a/hugr/benches/benchmarks/types.rs b/hugr/benches/benchmarks/types.rs index 5362511aa..a109a05d8 100644 --- a/hugr/benches/benchmarks/types.rs +++ b/hugr/benches/benchmarks/types.rs @@ -2,7 +2,7 @@ #![allow(clippy::unit_arg)] use hugr::extension::prelude::{QB_T, USIZE_T}; use hugr::ops::AliasDecl; -use hugr::types::{FunctionType, Type, TypeBound}; +use hugr::types::{Signature, Type, TypeBound}; use criterion::{black_box, criterion_group, AxisScale, Criterion, PlotConfiguration}; @@ -14,7 +14,7 @@ fn make_complex_type() -> Type { let b_register = Type::new_tuple(vec![int; 8]); let q_alias = Type::new_alias(AliasDecl::new("QReg", TypeBound::Any)); let sum = Type::new_sum([q_register, q_alias]); - Type::new_function(FunctionType::new(vec![sum], vec![b_register])) + Type::new_function(Signature::new(vec![sum], vec![b_register])) } fn bench_construction(c: &mut Criterion) { diff --git a/hugr/src/lib.rs b/hugr/src/lib.rs index f07cad689..f044181ac 100644 --- a/hugr/src/lib.rs +++ b/hugr/src/lib.rs @@ -31,7 +31,7 @@ //! use hugr::extension::prelude::{BOOL_T, QB_T}; //! use hugr::hugr::Hugr; //! use hugr::type_row; -//! use hugr::types::FunctionType; +//! use hugr::types::FuncValueType; //! //! // The type of qubits, `QB_T` is in the prelude but, by default, no gateset //! // is defined. This module provides Hadamard and CX gates. From 849fd35c3560414fdd4f4daa70294c6ef954c330 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 16 Jul 2024 10:45:38 +0100 Subject: [PATCH 109/115] Rename {in_out,endo}_{ft=>sig} --- hugr-core/src/builder.rs | 4 ++-- hugr-core/src/builder/cfg.rs | 6 +++--- hugr-core/src/builder/dataflow.rs | 12 ++++++------ hugr-core/src/extension/op_def.rs | 4 ++-- hugr-core/src/extension/prelude.rs | 10 +++++----- hugr-core/src/hugr/rewrite/inline_dfg.rs | 10 +++++----- hugr-core/src/hugr/rewrite/replace.rs | 4 ++-- hugr-core/src/hugr/rewrite/simple_replace.rs | 14 +++++++------- hugr-core/src/hugr/serialize/test.rs | 6 +++--- hugr-core/src/hugr/validate/test.rs | 6 +++--- hugr-core/src/hugr/views/sibling_subgraph.rs | 4 ++-- hugr-core/src/hugr/views/tests.rs | 10 +++++----- hugr-core/src/ops/constant.rs | 4 ++-- hugr-passes/src/const_fold.rs | 4 ++-- hugr-passes/src/const_fold/test.rs | 2 +- hugr-passes/src/force_order.rs | 4 ++-- hugr-passes/src/merge_bbs.rs | 8 ++++---- hugr-passes/src/nest_cfgs.rs | 20 ++++++++++---------- hugr/src/lib.rs | 4 ++-- 19 files changed, 68 insertions(+), 68 deletions(-) diff --git a/hugr-core/src/builder.rs b/hugr-core/src/builder.rs index 5f9388da8..3dd368a68 100644 --- a/hugr-core/src/builder.rs +++ b/hugr-core/src/builder.rs @@ -124,13 +124,13 @@ pub use circuit::{CircuitBuildError, CircuitBuilder}; /// Return a FunctionType with the same input and output types (specified) /// whose extension delta, when used in a non-FuncDefn container, will be inferred. -pub fn endo_ft(types: impl Into) -> Signature { +pub fn endo_sig(types: impl Into) -> Signature { Signature::new_endo(types).with_extension_delta(TO_BE_INFERRED) } /// Return a FunctionType with the specified input and output types /// whose extension delta, when used in a non-FuncDefn container, will be inferred. -pub fn inout_ft(inputs: impl Into, outputs: impl Into) -> Signature { +pub fn inout_sig(inputs: impl Into, outputs: impl Into) -> Signature { Signature::new(inputs, outputs).with_extension_delta(TO_BE_INFERRED) } diff --git a/hugr-core/src/builder/cfg.rs b/hugr-core/src/builder/cfg.rs index 4d8860615..8f974d8c5 100644 --- a/hugr-core/src/builder/cfg.rs +++ b/hugr-core/src/builder/cfg.rs @@ -46,7 +46,7 @@ use crate::{hugr::HugrMut, type_row, Hugr}; /// +------------+ /// */ /// use hugr::{ -/// builder::{BuildError, CFGBuilder, Container, Dataflow, HugrBuilder, endo_ft, inout_ft}, +/// builder::{BuildError, CFGBuilder, Container, Dataflow, HugrBuilder, endo_sig, inout_sig}, /// extension::{prelude, ExtensionSet}, /// ops, type_row, /// types::{Signature, SumType, Type}, @@ -84,7 +84,7 @@ use crate::{hugr::HugrMut, type_row, Hugr}; /// // `NAT` 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_ft(type_row![NAT, NAT], NAT), +/// inout_sig(type_row![NAT, NAT], NAT), /// 1, // only one successor to this block /// )?; /// let successor_a = { @@ -98,7 +98,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_ft(NAT), 1)?; +/// let mut successor_builder = cfg_builder.simple_block_builder(endo_sig(NAT), 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(); diff --git a/hugr-core/src/builder/dataflow.rs b/hugr-core/src/builder/dataflow.rs index 267e47a0f..99976397c 100644 --- a/hugr-core/src/builder/dataflow.rs +++ b/hugr-core/src/builder/dataflow.rs @@ -204,7 +204,7 @@ pub(crate) mod test { use crate::builder::build_traits::DataflowHugr; use crate::builder::{ - endo_ft, inout_ft, BuilderWiringError, DataflowSubContainer, ModuleBuilder, + endo_sig, inout_sig, BuilderWiringError, DataflowSubContainer, ModuleBuilder, }; use crate::extension::prelude::{BOOL_T, USIZE_T}; use crate::extension::{ExtensionId, EMPTY_REG, PRELUDE_REGISTRY}; @@ -226,7 +226,7 @@ pub(crate) mod test { #[test] fn nested_identity() -> Result<(), BuildError> { let build_result = { - let mut outer_builder = DFGBuilder::new(endo_ft(type_row![NAT, QB]))?; + let mut outer_builder = DFGBuilder::new(endo_sig(type_row![NAT, QB]))?; let [int, qb] = outer_builder.input_wires_arr(); @@ -250,7 +250,7 @@ pub(crate) mod test { F: FnOnce(&mut DFGBuilder) -> Result<(), BuildError>, { let build_result = { - let mut builder = DFGBuilder::new(inout_ft(BOOL_T, type_row![BOOL_T, BOOL_T]))?; + let mut builder = DFGBuilder::new(inout_sig(BOOL_T, type_row![BOOL_T, BOOL_T]))?; f(&mut builder)?; @@ -409,12 +409,12 @@ pub(crate) mod test { let xb: ExtensionId = "B".try_into().unwrap(); let xc: ExtensionId = "C".try_into().unwrap(); - let mut parent = DFGBuilder::new(endo_ft(BIT))?; + let mut parent = DFGBuilder::new(endo_sig(BIT))?; 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_ft(BIT), [w])?; + let mut add_ab = parent.dfg_builder(endo_sig(BIT), [w])?; let [w] = add_ab.input_wires_arr(); let lift_a = add_ab.add_dataflow_op( @@ -440,7 +440,7 @@ 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_ft(BIT), [w])?; + let mut add_c = parent.dfg_builder(endo_sig(BIT), [w])?; let [w] = add_c.input_wires_arr(); let lift_c = add_c.add_dataflow_op( Lift { diff --git a/hugr-core/src/extension/op_def.rs b/hugr-core/src/extension/op_def.rs index 2ec8af05f..0e28fc776 100644 --- a/hugr-core/src/extension/op_def.rs +++ b/hugr-core/src/extension/op_def.rs @@ -486,7 +486,7 @@ pub(super) mod test { use itertools::Itertools; use super::SignatureFromArgs; - use crate::builder::{endo_ft, DFGBuilder, Dataflow, DataflowHugr}; + 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::{ExtensionRegistry, ExtensionSet, PRELUDE}; @@ -608,7 +608,7 @@ pub(super) mod test { let list_usize = Type::new_extension(list_def.instantiate(vec![TypeArg::Type { ty: USIZE_T }])?); - let mut dfg = DFGBuilder::new(endo_ft(vec![list_usize]))?; + let mut dfg = DFGBuilder::new(endo_sig(vec![list_usize]))?; let rev = dfg.add_dataflow_op( CustomOp::new_extension( e.instantiate_extension_op(&OP_NAME, vec![TypeArg::Type { ty: USIZE_T }], ®) diff --git a/hugr-core/src/extension/prelude.rs b/hugr-core/src/extension/prelude.rs index 89ce1e906..12a61f19c 100644 --- a/hugr-core/src/extension/prelude.rs +++ b/hugr-core/src/extension/prelude.rs @@ -402,7 +402,7 @@ impl CustomConst for ConstExternalSymbol { #[cfg(test)] mod test { use crate::{ - builder::{endo_ft, inout_ft, DFGBuilder, Dataflow, DataflowHugr}, + builder::{endo_sig, inout_sig, DFGBuilder, Dataflow, DataflowHugr}, utils::test_quantum_extension::cx_gate, Hugr, Wire, }; @@ -412,7 +412,7 @@ mod test { #[test] /// Test building a HUGR involving a new_array operation. fn test_new_array() { - let mut b = DFGBuilder::new(inout_ft( + let mut b = DFGBuilder::new(inout_sig( vec![QB_T, QB_T], array_type(TypeArg::BoundedNat { n: 2 }, QB_T), )) @@ -452,7 +452,7 @@ mod test { assert!(error_val.equal_consts(&ConstError::new(2, "my message"))); assert!(!error_val.equal_consts(&ConstError::new(3, "my message"))); - let mut b = DFGBuilder::new(endo_ft(type_row![])).unwrap(); + let mut b = DFGBuilder::new(endo_sig(type_row![])).unwrap(); let err = b.add_load_value(error_val); @@ -486,7 +486,7 @@ mod test { ) .unwrap(); - let mut b = DFGBuilder::new(endo_ft(type_row![QB_T, QB_T])).unwrap(); + let mut b = DFGBuilder::new(endo_sig(type_row![QB_T, QB_T])).unwrap(); let [q0, q1] = b.input_wires_arr(); let [q0, q1] = b .add_dataflow_op(cx_gate(), [q0, q1]) @@ -524,7 +524,7 @@ mod test { #[test] /// Test print operation fn test_print() { - let mut b: DFGBuilder = DFGBuilder::new(endo_ft(vec![])).unwrap(); + let mut b: DFGBuilder = DFGBuilder::new(endo_sig(vec![])).unwrap(); let greeting: ConstString = ConstString::new("Hello, world!".into()); let greeting_out: Wire = b.add_load_value(greeting); let print_op = PRELUDE diff --git a/hugr-core/src/hugr/rewrite/inline_dfg.rs b/hugr-core/src/hugr/rewrite/inline_dfg.rs index b958e1ab8..281479b21 100644 --- a/hugr-core/src/hugr/rewrite/inline_dfg.rs +++ b/hugr-core/src/hugr/rewrite/inline_dfg.rs @@ -133,7 +133,7 @@ mod test { use rstest::rstest; use crate::builder::{ - endo_ft, inout_ft, Container, DFGBuilder, Dataflow, DataflowHugr, DataflowSubContainer, + endo_sig, inout_sig, Container, DFGBuilder, Dataflow, DataflowHugr, DataflowSubContainer, SubContainer, }; use crate::extension::prelude::QB_T; @@ -175,7 +175,7 @@ mod test { .unwrap(); let int_ty = &int_types::INT_TYPES[6]; - let mut outer = DFGBuilder::new(inout_ft(vec![int_ty.clone(); 2], vec![int_ty.clone()]))?; + let mut outer = DFGBuilder::new(inout_sig(vec![int_ty.clone(); 2], vec![int_ty.clone()]))?; let [a, b] = outer.input_wires_arr(); fn make_const + AsRef>( d: &mut DFGBuilder, @@ -245,7 +245,7 @@ mod test { #[test] fn permutation() -> Result<(), Box> { - let mut h = DFGBuilder::new(endo_ft(type_row![QB_T, QB_T]))?; + let mut h = DFGBuilder::new(endo_sig(type_row![QB_T, QB_T]))?; let [p, q] = h.input_wires_arr(); let [p_h] = h .add_dataflow_op(test_quantum_extension::h_gate(), [p])? @@ -340,11 +340,11 @@ mod test { PRELUDE.to_owned(), ]) .unwrap(); - let mut outer = DFGBuilder::new(endo_ft(type_row![QB_T, QB_T]))?; + let mut outer = DFGBuilder::new(endo_sig(type_row![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_ft(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/replace.rs b/hugr-core/src/hugr/rewrite/replace.rs index 65daa058f..bbee8c7e3 100644 --- a/hugr-core/src/hugr/rewrite/replace.rs +++ b/hugr-core/src/hugr/rewrite/replace.rs @@ -446,7 +446,7 @@ mod test { use itertools::Itertools; use crate::builder::{ - endo_ft, BuildError, CFGBuilder, Container, DFGBuilder, Dataflow, DataflowHugr, + endo_sig, BuildError, CFGBuilder, Container, DFGBuilder, Dataflow, DataflowHugr, DataflowSubContainer, HugrBuilder, SubContainer, }; use crate::extension::prelude::{BOOL_T, USIZE_T}; @@ -488,7 +488,7 @@ mod test { let just_list = TypeRow::from(vec![listy.clone()]); let intermed = TypeRow::from(vec![listy.clone(), USIZE_T]); - let mut cfg = CFGBuilder::new(endo_ft(just_list.clone()))?; + let mut cfg = CFGBuilder::new(endo_sig(just_list.clone()))?; let pred_const = cfg.add_constant(ops::Value::unary_unit_sum()); diff --git a/hugr-core/src/hugr/rewrite/simple_replace.rs b/hugr-core/src/hugr/rewrite/simple_replace.rs index d62de1ef3..a1cd8d57a 100644 --- a/hugr-core/src/hugr/rewrite/simple_replace.rs +++ b/hugr-core/src/hugr/rewrite/simple_replace.rs @@ -219,7 +219,7 @@ pub(in crate::hugr::rewrite) mod test { use std::collections::{HashMap, HashSet}; use crate::builder::{ - endo_ft, inout_ft, BuildError, Container, DFGBuilder, Dataflow, DataflowHugr, + endo_sig, inout_sig, BuildError, Container, DFGBuilder, Dataflow, DataflowHugr, DataflowSubContainer, HugrBuilder, ModuleBuilder, }; use crate::extension::prelude::BOOL_T; @@ -292,7 +292,7 @@ pub(in crate::hugr::rewrite) mod test { /// ┤ H ├┤ X ├ /// └───┘└───┘ fn make_dfg_hugr() -> Result { - let mut dfg_builder = DFGBuilder::new(endo_ft(type_row![QB, QB]))?; + let mut dfg_builder = DFGBuilder::new(endo_sig(type_row![QB, QB]))?; 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])?; @@ -312,7 +312,7 @@ pub(in crate::hugr::rewrite) mod test { /// ┤ H ├ /// └───┘ fn make_dfg_hugr2() -> Result { - let mut dfg_builder = DFGBuilder::new(endo_ft(type_row![QB, QB]))?; + let mut dfg_builder = DFGBuilder::new(endo_sig(type_row![QB, QB]))?; let [wire0, wire1] = dfg_builder.input_wires_arr(); let wire2 = dfg_builder.add_dataflow_op(h_gate(), vec![wire1])?; @@ -341,7 +341,7 @@ pub(in crate::hugr::rewrite) mod test { pub(in crate::hugr::rewrite) fn dfg_hugr_copy_bools() -> (Hugr, Vec) { fn build() -> Result<(Hugr, Vec), BuildError> { let mut dfg_builder = - DFGBuilder::new(inout_ft(type_row![BOOL_T], type_row![BOOL_T, BOOL_T]))?; + DFGBuilder::new(inout_sig(type_row![BOOL_T], type_row![BOOL_T, BOOL_T]))?; let [b] = dfg_builder.input_wires_arr(); let not_inp = dfg_builder.add_dataflow_op(NotOp, vec![b])?; @@ -518,7 +518,7 @@ pub(in crate::hugr::rewrite) mod test { #[test] fn test_replace_cx_cross() { let q_row: Vec = vec![QB, QB]; - let mut builder = DFGBuilder::new(endo_ft(q_row)).unwrap(); + 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(); circ.append(cx_gate(), [1, 0]).unwrap(); @@ -576,7 +576,7 @@ pub(in crate::hugr::rewrite) mod test { let one_bit = type_row![BOOL_T]; let two_bit = type_row![BOOL_T, BOOL_T]; - let mut builder = DFGBuilder::new(endo_ft(one_bit.clone())).unwrap(); + let mut builder = DFGBuilder::new(endo_sig(one_bit.clone())).unwrap(); let inw = builder.input_wires().exactly_one().unwrap(); let outw = builder .add_dataflow_op(and_op(), [inw, inw]) @@ -585,7 +585,7 @@ pub(in crate::hugr::rewrite) mod test { let [input, _] = builder.io(); let mut h = builder.finish_hugr_with_outputs(outw, &EMPTY_REG).unwrap(); - let mut builder = DFGBuilder::new(inout_ft(two_bit, one_bit)).unwrap(); + let mut builder = DFGBuilder::new(inout_sig(two_bit, one_bit)).unwrap(); let inw = builder.input_wires(); let outw = builder.add_dataflow_op(and_op(), inw).unwrap().outputs(); let [repl_input, repl_output] = builder.io(); diff --git a/hugr-core/src/hugr/serialize/test.rs b/hugr-core/src/hugr/serialize/test.rs index 9b7da8a4a..1822aa346 100644 --- a/hugr-core/src/hugr/serialize/test.rs +++ b/hugr-core/src/hugr/serialize/test.rs @@ -1,6 +1,6 @@ use super::*; use crate::builder::{ - endo_ft, inout_ft, test::closed_dfg_root_hugr, Container, DFGBuilder, Dataflow, DataflowHugr, + endo_sig, inout_sig, test::closed_dfg_root_hugr, Container, DFGBuilder, Dataflow, DataflowHugr, DataflowSubContainer, HugrBuilder, ModuleBuilder, }; use crate::extension::prelude::{BOOL_T, PRELUDE_ID, QB_T, USIZE_T}; @@ -314,7 +314,7 @@ fn dfg_roundtrip() -> Result<(), Box> { #[test] fn opaque_ops() -> Result<(), Box> { let tp: Vec = vec![BOOL_T; 1]; - let mut dfg = DFGBuilder::new(endo_ft(tp))?; + let mut dfg = DFGBuilder::new(endo_sig(tp))?; let [wire] = dfg.input_wires_arr(); // Add an extension operation @@ -367,7 +367,7 @@ fn hierarchy_order() -> Result<(), Box> { #[test] fn constants_roundtrip() -> Result<(), Box> { - let mut builder = DFGBuilder::new(inout_ft(vec![], INT_TYPES[4].clone())).unwrap(); + let mut builder = DFGBuilder::new(inout_sig(vec![], INT_TYPES[4].clone())).unwrap(); let w = builder.add_load_value(ConstInt::new_s(4, -2).unwrap()); let hugr = builder.finish_hugr_with_outputs([w], &INT_OPS_REGISTRY)?; diff --git a/hugr-core/src/hugr/validate/test.rs b/hugr-core/src/hugr/validate/test.rs index 4a9a65c24..bc31123f2 100644 --- a/hugr-core/src/hugr/validate/test.rs +++ b/hugr-core/src/hugr/validate/test.rs @@ -6,7 +6,7 @@ use cool_asserts::assert_matches; use super::*; use crate::builder::test::closed_dfg_root_hugr; use crate::builder::{ - inout_ft, BuildError, Container, DFGBuilder, Dataflow, DataflowHugr, DataflowSubContainer, + inout_sig, BuildError, Container, DFGBuilder, Dataflow, DataflowHugr, DataflowSubContainer, FunctionBuilder, HugrBuilder, ModuleBuilder, SubContainer, }; use crate::extension::prelude::{BOOL_T, PRELUDE, PRELUDE_ID, QB_T, USIZE_T}; @@ -603,7 +603,7 @@ fn instantiate_row_variables() -> Result<(), Box> { vec![TypeArg::Type { ty: USIZE_T }; i].into() } let e = extension_with_eval_parallel(); - let mut dfb = DFGBuilder::new(inout_ft( + let mut dfb = DFGBuilder::new(inout_sig( vec![ Type::new_function(Signature::new(USIZE_T, vec![USIZE_T, USIZE_T])), USIZE_T, @@ -709,7 +709,7 @@ fn test_polymorphic_call() -> Result<(), Box> { let int_pair = Type::new_tuple(type_row![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_ft( + let mut d = DFGBuilder::new(inout_sig( vec![utou(PRELUDE_ID), int_pair.clone()], vec![int_pair.clone()], ))?; diff --git a/hugr-core/src/hugr/views/sibling_subgraph.rs b/hugr-core/src/hugr/views/sibling_subgraph.rs index 0757895ce..53c92ed56 100644 --- a/hugr-core/src/hugr/views/sibling_subgraph.rs +++ b/hugr-core/src/hugr/views/sibling_subgraph.rs @@ -733,7 +733,7 @@ mod tests { use cool_asserts::assert_matches; - use crate::builder::inout_ft; + use crate::builder::inout_sig; use crate::extension::PRELUDE_REGISTRY; use crate::std_extensions::logic; use crate::utils::test_quantum_extension::{self, cx_gate}; @@ -1081,7 +1081,7 @@ mod tests { let one_bit = type_row![BOOL_T]; let two_bit = type_row![BOOL_T, BOOL_T]; - let mut builder = DFGBuilder::new(inout_ft(one_bit.clone(), two_bit.clone())).unwrap(); + let mut builder = DFGBuilder::new(inout_sig(one_bit.clone(), two_bit.clone())).unwrap(); let inw = builder.input_wires().exactly_one().unwrap(); let outw1 = builder.add_dataflow_op(NotOp, [inw]).unwrap().out_wire(0); let outw2 = builder diff --git a/hugr-core/src/hugr/views/tests.rs b/hugr-core/src/hugr/views/tests.rs index 2762bff80..8f1811656 100644 --- a/hugr-core/src/hugr/views/tests.rs +++ b/hugr-core/src/hugr/views/tests.rs @@ -3,7 +3,7 @@ use rstest::{fixture, rstest}; use crate::{ builder::{ - endo_ft, inout_ft, BuildError, BuildHandle, Container, DFGBuilder, Dataflow, DataflowHugr, + endo_sig, inout_sig, BuildError, BuildHandle, Container, DFGBuilder, Dataflow, DataflowHugr, }, extension::prelude::QB_T, ops::{ @@ -18,7 +18,7 @@ use crate::{ #[fixture] fn sample_hugr() -> (Hugr, BuildHandle, BuildHandle) { - let mut dfg = DFGBuilder::new(endo_ft(type_row![QB_T, QB_T])).unwrap(); + let mut dfg = DFGBuilder::new(endo_sig(type_row![QB_T, QB_T])).unwrap(); let [q1, q2] = dfg.input_wires_arr(); @@ -124,7 +124,7 @@ fn value_types() { use itertools::Itertools; let mut dfg = - DFGBuilder::new(inout_ft(type_row![QB_T, BOOL_T], type_row![BOOL_T, QB_T])).unwrap(); + DFGBuilder::new(inout_sig(type_row![QB_T, BOOL_T], type_row![BOOL_T, QB_T])).unwrap(); let [q, b] = dfg.input_wires_arr(); let n1 = dfg.add_dataflow_op(h_gate(), [q]).unwrap(); @@ -147,7 +147,7 @@ fn value_types() { fn static_targets() { use crate::extension::prelude::{ConstUsize, USIZE_T}; use itertools::Itertools; - let mut dfg = DFGBuilder::new(inout_ft(type_row![], type_row![USIZE_T])).unwrap(); + let mut dfg = DFGBuilder::new(inout_sig(type_row![], type_row![USIZE_T])).unwrap(); let c = dfg.add_constant(Value::extension(ConstUsize::new(1))); @@ -171,7 +171,7 @@ fn test_dataflow_ports_only() { use crate::std_extensions::logic::NotOp; use itertools::Itertools; - let mut dfg = DFGBuilder::new(endo_ft(BOOL_T)).unwrap(); + let mut dfg = DFGBuilder::new(endo_sig(BOOL_T)).unwrap(); let local_and = { let local_and = dfg .define_function( diff --git a/hugr-core/src/ops/constant.rs b/hugr-core/src/ops/constant.rs index 04b8d77cc..b14e64d3a 100644 --- a/hugr-core/src/ops/constant.rs +++ b/hugr-core/src/ops/constant.rs @@ -528,7 +528,7 @@ pub type ValueNameRef = str; #[cfg(test)] mod test { use super::Value; - use crate::builder::inout_ft; + use crate::builder::inout_sig; use crate::builder::test::simple_dfg_hugr; use crate::std_extensions::arithmetic::int_types::ConstInt; use crate::{ @@ -589,7 +589,7 @@ mod test { let pred_rows = vec![type_row![USIZE_T, FLOAT64_TYPE], Type::EMPTY_TYPEROW]; let pred_ty = SumType::new(pred_rows.clone()); - let mut b = DFGBuilder::new(inout_ft( + let mut b = DFGBuilder::new(inout_sig( type_row![], TypeRow::from(vec![pred_ty.clone().into()]), ))?; diff --git a/hugr-passes/src/const_fold.rs b/hugr-passes/src/const_fold.rs index c895256cd..3026e5779 100644 --- a/hugr-passes/src/const_fold.rs +++ b/hugr-passes/src/const_fold.rs @@ -2,7 +2,7 @@ use std::collections::{BTreeSet, HashMap}; -use hugr_core::builder::inout_ft; +use hugr_core::builder::inout_sig; use itertools::Itertools; use thiserror::Error; @@ -136,7 +136,7 @@ pub fn fold_leaf_op(op: &OpType, consts: &[(IncomingPort, Value)]) -> ConstFoldR /// against `reg`. fn const_graph(consts: Vec, reg: &ExtensionRegistry) -> Hugr { let const_types = consts.iter().map(Value::get_type).collect_vec(); - let mut b = DFGBuilder::new(inout_ft(type_row![], const_types)).unwrap(); + let mut b = DFGBuilder::new(inout_sig(type_row![], const_types)).unwrap(); let outputs = consts .into_iter() diff --git a/hugr-passes/src/const_fold/test.rs b/hugr-passes/src/const_fold/test.rs index 768bcffc7..8f3fed226 100644 --- a/hugr-passes/src/const_fold/test.rs +++ b/hugr-passes/src/const_fold/test.rs @@ -74,7 +74,7 @@ fn test_add(#[case] a: f64, #[case] b: f64, #[case] c: f64) { } fn noargfn(outputs: impl Into) -> Signature { - inout_ft(type_row![], outputs) + inout_sig(type_row![], outputs) } #[test] diff --git a/hugr-passes/src/force_order.rs b/hugr-passes/src/force_order.rs index 91e309786..cfbec1682 100644 --- a/hugr-passes/src/force_order.rs +++ b/hugr-passes/src/force_order.rs @@ -204,7 +204,7 @@ mod test { use std::collections::HashMap; use super::*; - use hugr_core::builder::{endo_ft, BuildHandle, Dataflow, DataflowHugr}; + use hugr_core::builder::{endo_sig, BuildHandle, Dataflow, DataflowHugr}; use hugr_core::extension::EMPTY_REG; use hugr_core::ops::handle::{DataflowOpID, NodeHandle}; @@ -247,7 +247,7 @@ mod test { /// Output fn test_hugr() -> (Hugr, [Node; 4]) { let t = INT_TYPES[I as usize].clone(); - let mut builder = DFGBuilder::new(endo_ft(vec![t.clone(), t.clone()])).unwrap(); + let mut builder = DFGBuilder::new(endo_sig(vec![t.clone(), t.clone()])).unwrap(); let [iw1, iw2] = builder.input_wires_arr(); let v0 = build_neg(&mut builder, iw1); let v1 = build_neg(&mut builder, iw2); diff --git a/hugr-passes/src/merge_bbs.rs b/hugr-passes/src/merge_bbs.rs index aaac004ad..fae6b061f 100644 --- a/hugr-passes/src/merge_bbs.rs +++ b/hugr-passes/src/merge_bbs.rs @@ -161,7 +161,7 @@ mod test { use itertools::Itertools; use rstest::rstest; - use hugr_core::builder::{endo_ft, inout_ft, CFGBuilder, DFGWrapper, Dataflow, HugrBuilder}; + 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::{ExtensionRegistry, PRELUDE, PRELUDE_REGISTRY}; use hugr_core::hugr::views::sibling::SiblingMut; @@ -226,7 +226,7 @@ mod test { let e = extension(); let tst_op = e.instantiate_extension_op("Test", [], &PRELUDE_REGISTRY)?; let reg = ExtensionRegistry::try_new([PRELUDE.to_owned(), e])?; - let mut h = CFGBuilder::new(inout_ft(loop_variants.clone(), exit_types.clone()))?; + 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 br = lifted_unary_unit_sum(&mut no_b1); @@ -245,7 +245,7 @@ mod test { let loop_backedge_target = if self_loop { no_b1 } else { - let mut no_b2 = h.simple_block_builder(endo_ft(loop_variants), 1)?; + 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 br = lifted_unary_unit_sum(&mut no_b2); let nid = no_b2.finish_with_outputs(br, n.outputs())?; @@ -321,7 +321,7 @@ mod test { .into_owned() .try_into() .unwrap(); - let mut h = CFGBuilder::new(inout_ft(QB_T, res_t.clone()))?; + 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 [inw] = bb1.input_wires_arr(); let load_cst = bb1.add_load_value(ConstUsize::new(1)); diff --git a/hugr-passes/src/nest_cfgs.rs b/hugr-passes/src/nest_cfgs.rs index 32d207844..617950f9e 100644 --- a/hugr-passes/src/nest_cfgs.rs +++ b/hugr-passes/src/nest_cfgs.rs @@ -575,7 +575,7 @@ impl EdgeClassifier { pub(crate) mod test { use super::*; use hugr_core::builder::{ - endo_ft, BuildError, CFGBuilder, Container, DataflowSubContainer, HugrBuilder, + endo_sig, BuildError, CFGBuilder, Container, DataflowSubContainer, HugrBuilder, }; use hugr_core::extension::PRELUDE_REGISTRY; use hugr_core::extension::{prelude::USIZE_T, ExtensionSet}; @@ -620,11 +620,11 @@ pub(crate) mod test { 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_ft(NAT), 1)?, + cfg_builder.simple_block_builder(endo_sig(NAT), 1)?, &const_unit, )?; let tail = n_identity( - cfg_builder.simple_block_builder(endo_ft(NAT), 2)?, + cfg_builder.simple_block_builder(endo_sig(NAT), 2)?, &pred_const, )?; cfg_builder.branch(&tail, 1, &head)?; @@ -851,7 +851,7 @@ pub(crate) mod test { const_pred: &ConstID, unit_const: &ConstID, ) -> Result<(BasicBlockID, BasicBlockID), BuildError> { - let split = n_identity(cfg.simple_block_builder(endo_ft(NAT), 2)?, const_pred)?; + let split = n_identity(cfg.simple_block_builder(endo_sig(NAT), 2)?, const_pred)?; let merge = build_then_else_merge_from_if(cfg, unit_const, split)?; Ok((split, merge)) } @@ -861,9 +861,9 @@ pub(crate) mod test { unit_const: &ConstID, split: BasicBlockID, ) -> Result { - let merge = n_identity(cfg.simple_block_builder(endo_ft(NAT), 1)?, unit_const)?; - let left = n_identity(cfg.simple_block_builder(endo_ft(NAT), 1)?, unit_const)?; - let right = n_identity(cfg.simple_block_builder(endo_ft(NAT), 1)?, unit_const)?; + 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)?; cfg.branch(&split, 0, &left)?; cfg.branch(&split, 1, &right)?; cfg.branch(&left, 0, &merge)?; @@ -887,7 +887,7 @@ pub(crate) mod test { 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_ft(NAT), 2)?, + cfg_builder.simple_block_builder(endo_sig(NAT), 2)?, &pred_const, )?; cfg_builder.branch(&tail, 1, &merge)?; @@ -924,7 +924,7 @@ pub(crate) mod test { let head = if separate_headers { let head = n_identity( - cfg_builder.simple_block_builder(endo_ft(NAT), 1)?, + cfg_builder.simple_block_builder(endo_sig(NAT), 1)?, &const_unit, )?; cfg_builder.branch(&head, 0, &split)?; @@ -934,7 +934,7 @@ pub(crate) mod test { split }; let tail = n_identity( - cfg_builder.simple_block_builder(endo_ft(NAT), 2)?, + cfg_builder.simple_block_builder(endo_sig(NAT), 2)?, &pred_const, )?; cfg_builder.branch(&tail, 1, &head)?; diff --git a/hugr/src/lib.rs b/hugr/src/lib.rs index f044181ac..f142cffc8 100644 --- a/hugr/src/lib.rs +++ b/hugr/src/lib.rs @@ -27,7 +27,7 @@ //! To build a HUGR for a simple quantum circuit and then serialize it to a buffer, we can define //! a simple quantum extension and then use the [[builder::DFGBuilder]] as follows: //! ``` -//! use hugr::builder::{BuildError, DFGBuilder, Dataflow, DataflowHugr, inout_ft}; +//! use hugr::builder::{BuildError, DFGBuilder, Dataflow, DataflowHugr, inout_sig}; //! use hugr::extension::prelude::{BOOL_T, QB_T}; //! use hugr::hugr::Hugr; //! use hugr::type_row; @@ -115,7 +115,7 @@ //! // └───┘└───┘└╥┘ //! // c: ╚═ //! fn make_dfg_hugr() -> Result { -//! let mut dfg_builder = DFGBuilder::new(inout_ft( +//! let mut dfg_builder = DFGBuilder::new(inout_sig( //! type_row![QB_T, QB_T], //! type_row![QB_T, QB_T, BOOL_T], //! ))?; From 889b91fb9e9e85d3b6d737ad2666ad7c78da0a97 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 16 Jul 2024 10:55:30 +0100 Subject: [PATCH 110/115] fix extension tests --- hugr-core/src/hugr/validate/test.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hugr-core/src/hugr/validate/test.rs b/hugr-core/src/hugr/validate/test.rs index bc31123f2..fbc847f1c 100644 --- a/hugr-core/src/hugr/validate/test.rs +++ b/hugr-core/src/hugr/validate/test.rs @@ -974,7 +974,7 @@ mod extension_tests { #[rstest] #[case::d1(|signature| ops::DFG {signature}.into())] - #[case::f1(|ft: FunctionType| ops::FuncDefn {name: "foo".to_string(), signature: ft.into()}.into())] + #[case::f1(|sig: Signature| ops::FuncDefn {name: "foo".to_string(), signature: sig.into()}.into())] #[case::c1(|signature| ops::Case {signature}.into())] fn parent_extension_mismatch( #[case] parent_f: impl Fn(Signature) -> OpType, From 46b54e3fe0dd2fcc5a99acda7fcfcf9619088f4c Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 16 Jul 2024 11:10:23 +0100 Subject: [PATCH 111/115] doc fixes --- hugr-core/src/extension/op_def.rs | 2 +- hugr-core/src/hugr/views.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/hugr-core/src/extension/op_def.rs b/hugr-core/src/extension/op_def.rs index 0e28fc776..c674a1312 100644 --- a/hugr-core/src/extension/op_def.rs +++ b/hugr-core/src/extension/op_def.rs @@ -218,7 +218,7 @@ impl SignatureFunc { } } - /// Compute the concrete signature ([FunctionType]). + /// Compute the concrete signature ([FuncValueType]). /// /// # Panics /// diff --git a/hugr-core/src/hugr/views.rs b/hugr-core/src/hugr/views.rs index c8f7ae9e3..6a52f33f0 100644 --- a/hugr-core/src/hugr/views.rs +++ b/hugr-core/src/hugr/views.rs @@ -332,7 +332,7 @@ pub trait HugrView: HugrInternals { /// graph. Otherwise, returns `None`. /// /// In contrast to [`poly_func_type`][HugrView::poly_func_type], this - /// method always return a concrete [`FunctionType`]. + /// method always return a concrete [`Signature`]. fn inner_function_type(&self) -> Option { self.root_type().inner_function_type() } From 58d66ff94056552d5c95c7521c6d0aa48a7a473a Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Tue, 16 Jul 2024 16:12:34 +0100 Subject: [PATCH 112/115] Give exact expected error in dataflow.rs / no_outer_row_variables --- hugr-core/src/builder/dataflow.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/hugr-core/src/builder/dataflow.rs b/hugr-core/src/builder/dataflow.rs index 43899520a..72dbee910 100644 --- a/hugr-core/src/builder/dataflow.rs +++ b/hugr-core/src/builder/dataflow.rs @@ -207,14 +207,14 @@ pub(crate) mod test { endo_sig, inout_sig, BuilderWiringError, DataflowSubContainer, ModuleBuilder, }; use crate::extension::prelude::{BOOL_T, USIZE_T}; - use crate::extension::{ExtensionId, EMPTY_REG, PRELUDE_REGISTRY}; + use crate::extension::{ExtensionId, SignatureError, EMPTY_REG, PRELUDE_REGISTRY}; use crate::hugr::validate::InterGraphEdgeError; use crate::ops::{handle::NodeHandle, Lift, Noop, OpTag}; use crate::ops::{OpTrait, Value}; use crate::std_extensions::logic::test::and_op; use crate::types::type_param::TypeParam; - use crate::types::{EdgeKind, FuncValueType, Signature, Type, TypeBound, TypeRV}; + 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}, @@ -531,7 +531,12 @@ pub(crate) mod test { [vec![USIZE_T.into()].into(), vec![tv.into()].into()], &PRELUDE_REGISTRY, ); - assert!(ev.is_err()); + assert_eq!( + ev, + Err(SignatureError::RowVarWhereTypeExpected { + var: RowVariable(0, TypeBound::Copyable) + }) + ); Ok(()) } From 40c989b7dfc294c2fa0756e2c55598026882a6d8 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Wed, 17 Jul 2024 10:37:49 +0100 Subject: [PATCH 113/115] Add From for SignatureFunc --- hugr-core/src/extension/op_def.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/hugr-core/src/extension/op_def.rs b/hugr-core/src/extension/op_def.rs index c674a1312..61b6cd8b8 100644 --- a/hugr-core/src/extension/op_def.rs +++ b/hugr-core/src/extension/op_def.rs @@ -11,7 +11,7 @@ use super::{ use crate::ops::{OpName, OpNameRef}; use crate::types::type_param::{check_type_args, TypeArg, TypeParam}; -use crate::types::{FuncValueType, PolyFuncTypeRV, Signature}; +use crate::types::{FuncValueType, PolyFuncType, PolyFuncTypeRV, Signature}; use crate::Hugr; /// Trait necessary for binary computations of OpDef signature @@ -186,6 +186,12 @@ impl From for SignatureFunc { } } +impl From for SignatureFunc { + fn from(value: PolyFuncType) -> Self { + Self::PolyFuncType(CustomValidator::from_polyfunc(value)) + } +} + impl From for SignatureFunc { fn from(v: PolyFuncTypeRV) -> Self { Self::PolyFuncType(CustomValidator::from_polyfunc(v)) From 17ea37e7ed2060d13943ef0e1311117396d92cd2 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Wed, 17 Jul 2024 10:48:36 +0100 Subject: [PATCH 114/115] Add TypeBase::try_into_type(), combine From> for TypeArg --- hugr-core/src/types.rs | 22 +++++++++++++++------- hugr-core/src/types/type_param.rs | 15 +++++---------- 2 files changed, 20 insertions(+), 17 deletions(-) diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index 9747fd0e0..83dbe8980 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -476,23 +476,31 @@ impl TypeRV { } // ====== Conversions ====== -impl TryFrom for Type { - type Error = RowVariable; - fn try_from(value: TypeRV) -> Result { - Ok(Self( - match value.0 { +impl TypeBase { + /// (Fallibly) converts a TypeBase (parameterized, so may or may not be able + /// to contain [RowVariables]) into a [Type] that definitely does not. + pub fn try_into_type(self) -> Result { + Ok(TypeBase( + match self.0 { TypeEnum::Extension(e) => TypeEnum::Extension(e), TypeEnum::Alias(a) => TypeEnum::Alias(a), TypeEnum::Function(f) => TypeEnum::Function(f), TypeEnum::Variable(idx, bound) => TypeEnum::Variable(idx, bound), - TypeEnum::RowVar(rv) => return Err(rv.as_rv().clone()), + TypeEnum::RowVar(rv) => Err(rv.as_rv().clone())?, TypeEnum::Sum(s) => TypeEnum::Sum(s), }, - value.1, + self.1, )) } } +impl TryFrom for Type { + type Error = RowVariable; + fn try_from(value: TypeRV) -> Result { + value.try_into_type() + } +} + impl TypeBase { /// A swiss-army-knife for any safe conversion of the type argument `RV1` /// to/from [NoRV]/RowVariable/rust-type-variable. diff --git a/hugr-core/src/types/type_param.rs b/hugr-core/src/types/type_param.rs index bfc5c04e3..273e9a656 100644 --- a/hugr-core/src/types/type_param.rs +++ b/hugr-core/src/types/type_param.rs @@ -14,7 +14,8 @@ use crate::extension::ExtensionRegistry; use crate::extension::ExtensionSet; use crate::extension::SignatureError; -use super::{check_typevar_decl, CustomType, RowVariable, Substitution, Type, TypeBound, TypeRV}; +use super::row_var::MaybeRV; +use super::{check_typevar_decl, CustomType, RowVariable, Substitution, Type, TypeBase, TypeBound}; /// The upper non-inclusive bound of a [`TypeParam::BoundedNat`] // A None inner value implies the maximum bound: u64::MAX + 1 (all u64 values valid) @@ -183,15 +184,9 @@ pub enum TypeArg { }, } -impl From for TypeArg { - fn from(ty: Type) -> Self { - TypeArg::Type { ty } - } -} - -impl From for TypeArg { - fn from(value: TypeRV) -> Self { - match value.try_into() { +impl From> for TypeArg { + fn from(value: TypeBase) -> Self { + match value.try_into_type() { Ok(ty) => TypeArg::Type { ty }, Err(RowVariable(idx, bound)) => TypeArg::new_var_use(idx, TypeParam::new_list(bound)), } From eb4152a345bfaa42d475e8ec224c1333eef22661 Mon Sep 17 00:00:00 2001 From: Alan Lawrence Date: Wed, 17 Jul 2024 10:55:48 +0100 Subject: [PATCH 115/115] oops, fix doc --- hugr-core/src/types.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hugr-core/src/types.rs b/hugr-core/src/types.rs index 83dbe8980..c1fb875fa 100644 --- a/hugr-core/src/types.rs +++ b/hugr-core/src/types.rs @@ -478,7 +478,7 @@ impl TypeRV { // ====== Conversions ====== impl TypeBase { /// (Fallibly) converts a TypeBase (parameterized, so may or may not be able - /// to contain [RowVariables]) into a [Type] that definitely does not. + /// to contain [RowVariable]s) into a [Type] that definitely does not. pub fn try_into_type(self) -> Result { Ok(TypeBase( match self.0 {