hugr_core/std_extensions/
ptr.rs

1//! Pointer type and operations.
2
3use std::sync::{Arc, Weak};
4
5use strum::{EnumIter, EnumString, IntoStaticStr};
6
7use crate::builder::{BuildError, Dataflow};
8use crate::extension::TypeDefBound;
9use crate::ops::OpName;
10use crate::types::{CustomType, PolyFuncType, Signature, Type, TypeBound, TypeName};
11use crate::Wire;
12use crate::{
13    extension::{
14        simple_op::{
15            HasConcrete, HasDef, MakeExtensionOp, MakeOpDef, MakeRegisteredOp, OpLoadError,
16        },
17        ExtensionId, OpDef, SignatureError, SignatureFunc,
18    },
19    ops::custom::ExtensionOp,
20    type_row,
21    types::type_param::{TypeArg, TypeParam},
22    Extension,
23};
24use lazy_static::lazy_static;
25#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, EnumIter, IntoStaticStr, EnumString)]
26#[allow(missing_docs)]
27#[non_exhaustive]
28/// Pointer operation definitions.
29pub enum PtrOpDef {
30    /// Create a new pointer.
31    New,
32    /// Read a value from a pointer.
33    Read,
34    /// Write a value to a pointer.
35    Write,
36}
37
38impl PtrOpDef {
39    /// Create a new concrete pointer operation with the given value type.
40    pub fn with_type(self, ty: Type) -> PtrOp {
41        PtrOp::new(self, ty)
42    }
43}
44
45impl MakeOpDef for PtrOpDef {
46    fn opdef_id(&self) -> OpName {
47        <&'static str>::from(self).into()
48    }
49
50    fn from_def(op_def: &OpDef) -> Result<Self, OpLoadError>
51    where
52        Self: Sized,
53    {
54        crate::extension::simple_op::try_from_name(op_def.name(), op_def.extension_id())
55    }
56
57    fn init_signature(&self, extension_ref: &Weak<Extension>) -> SignatureFunc {
58        let ptr_t: Type =
59            ptr_custom_type(Type::new_var_use(0, TypeBound::Copyable), extension_ref).into();
60        let inner_t = Type::new_var_use(0, TypeBound::Copyable);
61        let body = match self {
62            PtrOpDef::New => Signature::new(inner_t, ptr_t),
63            PtrOpDef::Read => Signature::new(ptr_t, inner_t),
64            PtrOpDef::Write => Signature::new(vec![ptr_t, inner_t], type_row![]),
65        };
66
67        PolyFuncType::new(TYPE_PARAMS, body).into()
68    }
69
70    fn extension(&self) -> ExtensionId {
71        EXTENSION_ID
72    }
73
74    fn extension_ref(&self) -> Weak<Extension> {
75        Arc::downgrade(&EXTENSION)
76    }
77
78    fn description(&self) -> String {
79        match self {
80            PtrOpDef::New => "Create a new pointer from a value.".into(),
81            PtrOpDef::Read => "Read a value from a pointer.".into(),
82            PtrOpDef::Write => "Write a value to a pointer, overwriting existing value.".into(),
83        }
84    }
85}
86
87/// Name of pointer extension.
88pub const EXTENSION_ID: ExtensionId = ExtensionId::new_unchecked("ptr");
89/// Name of pointer type.
90pub const PTR_TYPE_ID: TypeName = TypeName::new_inline("ptr");
91const TYPE_PARAMS: [TypeParam; 1] = [TypeParam::Type {
92    b: TypeBound::Copyable,
93}];
94/// Extension version.
95pub const VERSION: semver::Version = semver::Version::new(0, 1, 0);
96
97/// Extension for pointer operations.
98fn extension() -> Arc<Extension> {
99    Extension::new_arc(EXTENSION_ID, VERSION, |extension, extension_ref| {
100        extension
101            .add_type(
102                PTR_TYPE_ID,
103                TYPE_PARAMS.into(),
104                "Standard extension pointer type.".into(),
105                TypeDefBound::copyable(),
106                extension_ref,
107            )
108            .unwrap();
109        PtrOpDef::load_all_ops(extension, extension_ref).unwrap();
110    })
111}
112
113lazy_static! {
114    /// Reference to the pointer Extension.
115    pub static ref EXTENSION: Arc<Extension> = extension();
116}
117
118/// Integer type of a given bit width (specified by the TypeArg).  Depending on
119/// the operation, the semantic interpretation may be unsigned integer, signed
120/// integer or bit string.
121fn ptr_custom_type(ty: impl Into<Type>, extension_ref: &Weak<Extension>) -> CustomType {
122    let ty = ty.into();
123    CustomType::new(
124        PTR_TYPE_ID,
125        [ty.into()],
126        EXTENSION_ID,
127        TypeBound::Copyable,
128        extension_ref,
129    )
130}
131
132/// Integer type of a given bit width (specified by the TypeArg).
133pub fn ptr_type(ty: impl Into<Type>) -> Type {
134    ptr_custom_type(ty, &Arc::<Extension>::downgrade(&EXTENSION)).into()
135}
136
137#[derive(Clone, Debug, PartialEq)]
138/// A concrete pointer operation.
139pub struct PtrOp {
140    /// The operation definition.
141    pub def: PtrOpDef,
142    /// Type of the value being pointed to.
143    pub ty: Type,
144}
145
146impl PtrOp {
147    fn new(op: PtrOpDef, ty: Type) -> Self {
148        Self { def: op, ty }
149    }
150}
151
152impl MakeExtensionOp for PtrOp {
153    fn op_id(&self) -> OpName {
154        self.def.opdef_id()
155    }
156
157    fn from_extension_op(ext_op: &ExtensionOp) -> Result<Self, OpLoadError> {
158        let def = PtrOpDef::from_def(ext_op.def())?;
159        def.instantiate(ext_op.args())
160    }
161
162    fn type_args(&self) -> Vec<TypeArg> {
163        vec![self.ty.clone().into()]
164    }
165}
166
167impl MakeRegisteredOp for PtrOp {
168    fn extension_id(&self) -> ExtensionId {
169        EXTENSION_ID.to_owned()
170    }
171
172    fn extension_ref(&self) -> Weak<Extension> {
173        Arc::downgrade(&EXTENSION)
174    }
175}
176
177/// An extension trait for [Dataflow] providing methods to add pointer
178/// operations.
179pub trait PtrOpBuilder: Dataflow {
180    /// Add a "ptr.New" op.
181    fn add_new_ptr(&mut self, val_wire: Wire) -> Result<Wire, BuildError> {
182        let ty = self.get_wire_type(val_wire)?;
183        let handle = self.add_dataflow_op(PtrOpDef::New.with_type(ty), [val_wire])?;
184
185        Ok(handle.out_wire(0))
186    }
187
188    /// Add a "ptr.Read" op.
189    fn add_read_ptr(&mut self, ptr_wire: Wire, ty: Type) -> Result<Wire, BuildError> {
190        let handle = self.add_dataflow_op(PtrOpDef::Read.with_type(ty.clone()), [ptr_wire])?;
191        Ok(handle.out_wire(0))
192    }
193
194    /// Add a "ptr.Write" op.
195    fn add_write_ptr(&mut self, ptr_wire: Wire, val_wire: Wire) -> Result<(), BuildError> {
196        let ty = self.get_wire_type(val_wire)?;
197
198        let handle = self.add_dataflow_op(PtrOpDef::Write.with_type(ty), [ptr_wire, val_wire])?;
199        debug_assert_eq!(handle.outputs().len(), 0);
200        Ok(())
201    }
202}
203
204impl<D: Dataflow> PtrOpBuilder for D {}
205
206impl HasConcrete for PtrOpDef {
207    type Concrete = PtrOp;
208
209    fn instantiate(&self, type_args: &[TypeArg]) -> Result<Self::Concrete, OpLoadError> {
210        let ty = match type_args {
211            [TypeArg::Type { ty }] => ty.clone(),
212            _ => return Err(SignatureError::InvalidTypeArgs.into()),
213        };
214
215        Ok(self.with_type(ty))
216    }
217}
218
219impl HasDef for PtrOp {
220    type Def = PtrOpDef;
221}
222
223#[cfg(test)]
224pub(crate) mod test {
225    use crate::builder::DFGBuilder;
226    use crate::extension::prelude::bool_t;
227    use crate::ops::ExtensionOp;
228    use crate::HugrView;
229    use crate::{
230        builder::{Dataflow, DataflowHugr},
231        std_extensions::arithmetic::int_types::INT_TYPES,
232    };
233    use cool_asserts::assert_matches;
234    use std::sync::Arc;
235    use strum::IntoEnumIterator;
236
237    use super::*;
238    use crate::std_extensions::arithmetic::float_types::float64_type;
239    fn get_opdef(op: impl Into<&'static str>) -> Option<&'static Arc<OpDef>> {
240        EXTENSION.get_op(op.into())
241    }
242
243    #[test]
244    fn create_extension() {
245        assert_eq!(EXTENSION.name(), &EXTENSION_ID);
246
247        for o in PtrOpDef::iter() {
248            assert_eq!(PtrOpDef::from_def(get_opdef(o).unwrap()), Ok(o));
249        }
250    }
251
252    #[test]
253    fn test_ops() {
254        let ops = [
255            PtrOp::new(PtrOpDef::New, bool_t().clone()),
256            PtrOp::new(PtrOpDef::Read, float64_type()),
257            PtrOp::new(PtrOpDef::Write, INT_TYPES[5].clone()),
258        ];
259        for op in ops {
260            let op_t: ExtensionOp = op.clone().to_extension_op().unwrap();
261            let def_op = PtrOpDef::from_op(&op_t).unwrap();
262            assert_eq!(op.def, def_op);
263            let new_op = PtrOp::from_op(&op_t).unwrap();
264            assert_eq!(new_op, op);
265        }
266    }
267
268    #[test]
269    fn test_build() {
270        let in_row = vec![bool_t(), float64_type()];
271
272        let hugr = {
273            let mut builder = DFGBuilder::new(Signature::new(in_row.clone(), type_row![])).unwrap();
274
275            let in_wires: [Wire; 2] = builder.input_wires_arr();
276            for (ty, w) in in_row.into_iter().zip(in_wires.iter()) {
277                let new_ptr = builder.add_new_ptr(*w).unwrap();
278                let read = builder.add_read_ptr(new_ptr, ty).unwrap();
279                builder.add_write_ptr(new_ptr, read).unwrap();
280            }
281
282            builder.finish_hugr_with_outputs([]).unwrap()
283        };
284        assert_matches!(hugr.validate(), Ok(_));
285    }
286}