hugr-core 0.27.1

Quantinuum's Hierarchical Unified Graph Representation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
//! Builder trait for array operations in the dataflow graph.

use crate::std_extensions::collections::array::GenericArrayOpDef;
use crate::std_extensions::collections::borrow_array::BorrowArray;
use crate::{
    Wire,
    builder::{BuildError, Dataflow},
    extension::simple_op::HasConcrete as _,
    types::Type,
};
use itertools::Itertools as _;

use super::{Array, ArrayKind, GenericArrayClone, GenericArrayDiscard};

use crate::extension::prelude::{
    ConstUsize, UnwrapBuilder as _, either_type, option_type, usize_t,
};

/// Trait for building array operations in a dataflow graph that are generic
/// over the concrete array implementation.
pub trait GenericArrayOpBuilder: Dataflow {
    /// Adds a new array operation to the dataflow graph and return the wire
    /// representing the new array.
    ///
    /// # Arguments
    ///
    /// * `elem_ty` - The type of the elements in the array.
    /// * `values` - An iterator over the values to initialize the array with.
    ///
    /// # Errors
    ///
    /// If building the operation fails.
    ///
    /// # Returns
    ///
    /// The wire representing the new array.
    fn add_new_generic_array<AK: ArrayKind>(
        &mut self,
        elem_ty: Type,
        values: impl IntoIterator<Item = Wire>,
    ) -> Result<Wire, BuildError> {
        let inputs = values.into_iter().collect_vec();
        let [out] = self
            .add_dataflow_op(
                GenericArrayOpDef::<AK>::new_array.to_concrete(elem_ty, inputs.len() as u64),
                inputs,
            )?
            .outputs_arr();
        Ok(out)
    }

    /// Adds an array unpack operation to the dataflow graph.
    ///
    /// This operation unpacks an array into individual elements.
    ///
    /// # Arguments
    ///
    /// * `elem_ty` - The type of the elements in the array.
    /// * `size` - The size of the array.
    /// * `input` - The wire representing the array.
    ///
    /// # Errors
    ///
    /// Returns an error if building the operation fails.
    ///
    /// # Returns
    ///
    /// A vector of wires representing the individual elements of the array.
    fn add_generic_array_unpack<AK: ArrayKind>(
        &mut self,
        elem_ty: Type,
        size: u64,
        input: Wire,
    ) -> Result<Vec<Wire>, BuildError> {
        let op = GenericArrayOpDef::<AK>::unpack.instantiate(&[size.into(), elem_ty.into()])?;
        Ok(self.add_dataflow_op(op, vec![input])?.outputs().collect())
    }
    /// Adds an array clone operation to the dataflow graph and return the wires
    /// representing the originala and cloned array.
    ///
    /// # Arguments
    ///
    /// * `elem_ty` - The type of the elements in the array.
    /// * `size` - The size of the array.
    /// * `input` - The wire representing the array.
    ///
    /// # Errors
    ///
    /// If building the operation fails.
    ///
    /// # Returns
    ///
    /// The wires representing the original and cloned array.
    fn add_generic_array_clone<AK: ArrayKind>(
        &mut self,
        elem_ty: Type,
        size: u64,
        input: Wire,
    ) -> Result<(Wire, Wire), BuildError> {
        let op = GenericArrayClone::<AK>::new(elem_ty, size).unwrap();
        let [arr1, arr2] = self.add_dataflow_op(op, vec![input])?.outputs_arr();
        Ok((arr1, arr2))
    }

    /// Adds an array discard operation to the dataflow graph.
    ///
    /// # Arguments
    ///
    /// * `elem_ty` - The type of the elements in the array.
    /// * `size` - The size of the array.
    /// * `input` - The wire representing the array.
    ///
    /// # Errors
    ///
    /// If building the operation fails.
    fn add_generic_array_discard<AK: ArrayKind>(
        &mut self,
        elem_ty: Type,
        size: u64,
        input: Wire,
    ) -> Result<(), BuildError> {
        let op = GenericArrayDiscard::<AK>::new(elem_ty, size).unwrap();
        let [] = self.add_dataflow_op(op, vec![input])?.outputs_arr();
        Ok(())
    }

    /// Adds an array get operation to the dataflow graph.
    ///
    /// # Arguments
    ///
    /// * `elem_ty` - The type of the elements in the array.
    /// * `size` - The size of the array.
    /// * `input` - The wire representing the array.
    /// * `index` - The wire representing the index to get.
    ///
    /// # Errors
    ///
    /// If building the operation fails.
    ///
    /// # Returns
    ///
    /// * The wire representing the value at the specified index in the array
    /// * The wire representing the array
    fn add_generic_array_get<AK: ArrayKind>(
        &mut self,
        elem_ty: Type,
        size: u64,
        input: Wire,
        index: Wire,
    ) -> Result<(Wire, Wire), BuildError> {
        let op = GenericArrayOpDef::<AK>::get.instantiate(&[size.into(), elem_ty.into()])?;
        let [out, arr] = self.add_dataflow_op(op, vec![input, index])?.outputs_arr();
        Ok((out, arr))
    }

    /// Adds an array set operation to the dataflow graph.
    ///
    /// This operation sets the value at a specified index in the array.
    ///
    /// # Arguments
    ///
    /// * `elem_ty` - The type of the elements in the array.
    /// * `size` - The size of the array.
    /// * `input` - The wire representing the array.
    /// * `index` - The wire representing the index to set.
    /// * `value` - The wire representing the value to set at the specified index.
    ///
    /// # Errors
    ///
    /// Returns an error if building the operation fails.
    ///
    /// # Returns
    ///
    /// The wire representing the updated array after the set operation.
    fn add_generic_array_set<AK: ArrayKind>(
        &mut self,
        elem_ty: Type,
        size: u64,
        input: Wire,
        index: Wire,
        value: Wire,
    ) -> Result<Wire, BuildError> {
        let op = GenericArrayOpDef::<AK>::set.instantiate(&[size.into(), elem_ty.into()])?;
        let [out] = self
            .add_dataflow_op(op, vec![input, index, value])?
            .outputs_arr();
        Ok(out)
    }

    /// Adds an array swap operation to the dataflow graph.
    ///
    /// This operation swaps the values at two specified indices in the array.
    ///
    /// # Arguments
    ///
    /// * `elem_ty` - The type of the elements in the array.
    /// * `size` - The size of the array.
    /// * `input` - The wire representing the array.
    /// * `index1` - The wire representing the first index to swap.
    /// * `index2` - The wire representing the second index to swap.
    ///
    /// # Errors
    ///
    /// Returns an error if building the operation fails.
    ///
    /// # Returns
    ///
    /// The wire representing the updated array after the swap operation.
    fn add_generic_array_swap<AK: ArrayKind>(
        &mut self,
        elem_ty: Type,
        size: u64,
        input: Wire,
        index1: Wire,
        index2: Wire,
    ) -> Result<Wire, BuildError> {
        let op = GenericArrayOpDef::<AK>::swap.instantiate(&[size.into(), elem_ty.into()])?;
        let [out] = self
            .add_dataflow_op(op, vec![input, index1, index2])?
            .outputs_arr();
        Ok(out)
    }

    /// Adds an array pop-left operation to the dataflow graph.
    ///
    /// This operation removes the leftmost element from the array.
    ///
    /// # Arguments
    ///
    /// * `elem_ty` - The type of the elements in the array.
    /// * `size` - The size of the array.
    /// * `input` - The wire representing the array.
    ///
    /// # Errors
    ///
    /// Returns an error if building the operation fails.
    ///
    /// # Returns
    ///
    /// The wire representing the Option<elemty, array<SIZE-1, elemty>>
    fn add_generic_array_pop_left<AK: ArrayKind>(
        &mut self,
        elem_ty: Type,
        size: u64,
        input: Wire,
    ) -> Result<Wire, BuildError> {
        let op = GenericArrayOpDef::<AK>::pop_left.instantiate(&[size.into(), elem_ty.into()])?;
        Ok(self.add_dataflow_op(op, vec![input])?.out_wire(0))
    }

    /// Adds an array pop-right operation to the dataflow graph.
    ///
    /// This operation removes the rightmost element from the array.
    ///
    /// # Arguments
    ///
    /// * `elem_ty` - The type of the elements in the array.
    /// * `size` - The size of the array.
    /// * `input` - The wire representing the array.
    ///
    /// # Errors
    ///
    /// Returns an error if building the operation fails.
    ///
    /// # Returns
    ///
    /// The wire representing the Option<elemty, array<SIZE-1, elemty>>
    fn add_generic_array_pop_right<AK: ArrayKind>(
        &mut self,
        elem_ty: Type,
        size: u64,
        input: Wire,
    ) -> Result<Wire, BuildError> {
        let op = GenericArrayOpDef::<AK>::pop_right.instantiate(&[size.into(), elem_ty.into()])?;
        Ok(self.add_dataflow_op(op, vec![input])?.out_wire(0))
    }

    /// Adds an operation to discard an empty array from the dataflow graph.
    ///
    /// # Arguments
    ///
    /// * `elem_ty` - The type of the elements in the array.
    /// * `input` - The wire representing the array.
    ///
    /// # Errors
    ///
    /// Returns an error if building the operation fails.
    fn add_generic_array_discard_empty<AK: ArrayKind>(
        &mut self,
        elem_ty: Type,
        input: Wire,
    ) -> Result<(), BuildError> {
        self.add_dataflow_op(
            GenericArrayOpDef::<AK>::discard_empty
                .instantiate(&[elem_ty.into()])
                .unwrap(),
            [input],
        )?;
        Ok(())
    }
}

impl<D: Dataflow> GenericArrayOpBuilder for D {}

/// Helper function to build a Hugr that contains all basic array operations.
///
/// Generic over the concrete array implementation.
pub fn build_all_array_ops_generic<B: Dataflow, AK: ArrayKind>(mut builder: B) -> B {
    let us0 = builder.add_load_value(ConstUsize::new(0));
    let us1 = builder.add_load_value(ConstUsize::new(1));
    let us2 = builder.add_load_value(ConstUsize::new(2));
    let arr = builder
        .add_new_generic_array::<AK>(usize_t(), [us1, us2])
        .unwrap();

    // Add array unpack operation
    let [_us1, _us2] = builder
        .add_generic_array_unpack::<AK>(usize_t(), 2, arr)
        .unwrap()
        .try_into()
        .unwrap();

    let arr = builder
        .add_new_generic_array::<AK>(usize_t(), [us1, us2])
        .unwrap();
    let [arr] = {
        let r = builder
            .add_generic_array_swap::<AK>(usize_t(), 2, arr, us0, us1)
            .unwrap();
        let res_sum_ty = {
            let array_type = AK::ty(2, usize_t());
            either_type([array_type.clone()], [array_type])
        };
        builder.build_unwrap_sum(1, res_sum_ty, r).unwrap()
    };

    let ([elem_0], arr) = {
        let (r, arr) = builder
            .add_generic_array_get::<AK>(usize_t(), 2, arr, us0)
            .unwrap();
        (
            builder
                .build_unwrap_sum(1, option_type([usize_t()]), r)
                .unwrap(),
            arr,
        )
    };

    let [_elem_1, arr] = {
        let r = builder
            .add_generic_array_set::<AK>(usize_t(), 2, arr, us1, elem_0)
            .unwrap();
        let res_sum_ty = {
            let row = vec![usize_t(), AK::ty(2, usize_t())];
            either_type(row.clone(), row)
        };
        builder.build_unwrap_sum(1, res_sum_ty, r).unwrap()
    };

    let [_elem_left, arr] = {
        let r = builder
            .add_generic_array_pop_left::<AK>(usize_t(), 2, arr)
            .unwrap();
        builder
            .build_unwrap_sum(1, option_type(vec![usize_t(), AK::ty(1, usize_t())]), r)
            .unwrap()
    };
    let [_elem_right, arr] = {
        let r = builder
            .add_generic_array_pop_right::<AK>(usize_t(), 1, arr)
            .unwrap();
        builder
            .build_unwrap_sum(1, option_type(vec![usize_t(), AK::ty(0, usize_t())]), r)
            .unwrap()
    };

    builder
        .add_generic_array_discard_empty::<AK>(usize_t(), arr)
        .unwrap();
    builder
}

/// Helper function to build a Hugr that contains all basic array operations.
pub fn build_all_array_ops<B: Dataflow>(builder: B) -> B {
    build_all_array_ops_generic::<B, Array>(builder)
}

/// Helper function to build a Hugr that contains all basic array operations.
pub fn build_all_borrow_array_ops<B: Dataflow>(builder: B) -> B {
    build_all_array_ops_generic::<B, BorrowArray>(builder)
}

/// Testing utilities to generate Hugrs that contain array operations.
#[cfg(test)]
mod test {
    use crate::builder::{DFGBuilder, HugrBuilder};
    use crate::types::Signature;

    use super::*;

    #[test]
    fn all_array_ops() {
        let sig = Signature::new_endo(Type::EMPTY_TYPEROW);
        let builder = DFGBuilder::new(sig).unwrap();
        build_all_array_ops(builder).finish_hugr().unwrap();
    }

    #[test]
    fn all_borrow_array_ops() {
        let sig = Signature::new_endo(Type::EMPTY_TYPEROW);
        let builder = DFGBuilder::new(sig).unwrap();
        build_all_borrow_array_ops(builder).finish_hugr().unwrap();
    }
}