quil-rs 0.37.1

Rust tooling for Quil (Quantum Instruction Language)
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
//! Macros for generating the built-in waveform types
//!
//! We have to declare a bunch of waveforms which all look very similar but have slightly different
//! contents.  This is done in the `define_waveforms!` macro block below, but to get there, we have
//! to define a number of helper macros.
//!
//! For details on usage, see the parent module.
//!
//! The generated Python API is as follows:
//!
//! 1. A module `quilpy_waveforms` exporting, for every waveform that has fields, a `Py$waveform`
//!    type that wraps `$waveform<Pythonic>`; if the waveform does not have fields, then `$waveform`
//!    is exposed directly to Python.
//!
//! 2. A Python keyword-only constructor, a Python wrapper for `iq_values_at_sample_rate`, and a
//!    custom `__repr__` that produces output that looks like Python, all defined on `Py$waveform`
//!    for normal waveforms and `$waveform` for fieldless waveforms.
//!
//! 3. Getters and setters for all the fields of the `Py$waveform` type.
//!
//! 4. A way to get the Python repr from Rust, defined on the underlying `$waveform` types:
//!
//!    - A `pub(crate) fn __repr__(&self) -> &'static str` function `py_repr` function on any
//!      fieldless `$waveform`
//!
//!    - A `pub(crate) fn py_repr<'py>(&self, py: Python<'py>) -> PyResult<String>` function on all
//!      other `$waveform<Pythonic>`s.

/// Given a [`super::WaveformData`] marker, convert one of the field pseudo-types into the
/// corresponding actual Rust type.  Non-identifier types must be wrapped in parentheses because
/// macros can't match balanced angle brackets.
macro_rules! field_type {
    ($waveform_type:ident, $field_type:ident) => {
        field_type!(($waveform_type), $field_type)
    };
    (($($waveform_type:tt)+), ConcreteReal) => {
        f64
    };
    (($($waveform_type:tt)+), Real) => {
        $($waveform_type)+::Real
    };
    (($($waveform_type:tt)+), Complex) => {
        $($waveform_type)+::Complex
    };
}

/// `extract_type_if_generic_field!($pseudo_type; ...)` evaluates to `T::$pseudo_type` for the
/// `$pseudo_type`s `Real` and `Complex` if they occur in the type list `...`, and to `()`
/// otherwise.
///
/// This lets us e.g. get the appropriate [`Copy`] bounds on our types with [`derive_where`], since
/// `()` trivially satisfies the bounds.
macro_rules! extract_type_if_generic_field {
    (Real; Real $($rest:tt)*) => {
        T::Real
    };
    (Complex; Complex $($rest:tt)*) => {
        T::Complex
    };
    ($ty:ident; $other:tt $($rest:tt)*) => {
        extract_type_if_generic_field!($ty; $($rest)*)
    };
    ($ty:ident;) => {
        ()
    };
}

/// Part of the implementation of the `as_ref` function for waveforms; given a reference to a
/// pseudo-typed field `$field_ref: $pseudo_type`, either dereference it (if it's concrete) or leave
/// it alone (if it isn't concrete).
macro_rules! field_referencer {
    (ConcreteReal, $field_ref:expr) => {
        *$field_ref
    };
    (Real, $field_ref:expr) => {
        $field_ref
    };
    (Complex, $field_ref:expr) => {
        $field_ref
    };
}

/// Part of the implementation of the `try_evaluate` function for waveforms; given a pseudo-typed
/// field `$field: $pseudo_type` and the `$real` and `$complex` evaluator parameters to
/// `try_evaluate`, `field_evaluator!($pseudo_type, real = $real, complex = $complex, field)` will
/// transform that `field` from one [`super::WaveformData`] to another.
macro_rules! field_evaluator {
    (ConcreteReal, real = $real:ident, complex = $complex:ident, $field:expr) => {
        $field
    };
    (Real, real = $real:ident, complex = $complex:ident, $field:expr) => {
        $real($field)?
    };
    (Complex, real = $real:ident, complex = $complex:ident, $field:expr) => {
        $complex($field)?
    };
}

/// Part of the implementation of the `transpose` function for waveforms; properly propagates
/// optionality for non-concrete fields and just passes the concrete ones along.
macro_rules! field_transposer {
    ($field:ident, ConcreteReal) => {
        $field
    };
    ($field:ident, Real) => {
        $field?
    };
    ($field:ident, Complex) => {
        $field?
    };
}

/// Constant strings documenting the origin of waveforms, powering the `#[waveform_source(...)]`
/// attribute within [`define_waveforms!`].
macro_rules! waveform_source {
    (QuilT) => {
        r#"This waveform is part of the [Quil-T][] spec ([§12.2, Waveforms][]).

[Quil-T]: https://quil-lang.github.io/#12Annex-T--Pulse-Level-Control
[§12.2, Waveforms]: https://quil-lang.github.io/#12-2Waveforms"#
    };
    (Rigetti) => {
        r#"This waveform is a Rigetti extension to Quil-T."#
    };
}

/// `instantiated_waveform!($path<$instantiation>, ...fields of $path...)` is effectively the same
/// as `$path<$instantiation>`, except that it just emits `$path` if there are no fields since
/// fieldless waveforms aren't generic.
macro_rules! instantiated_waveform {
    ($($path:ident)::+<$parameter:ty>, $($field:ident)+) => {
        $($path)::+<$parameter>
    };
    ($($path:ident)::+<$parameter:ty>,) => {
         $($path)::+
     };
}

/// `transpose_if_generic_waveform!($value, ...fields of the type of $value...)` computes the
/// transpose of `$value`: either `$value.transpose()` if `$value` is of generic type, or the
/// trivial always-successful tranpose `Some($value)` if `$value` is of nongeneric type.
macro_rules! transpose_if_generic_waveform {
    ($value:expr, $($field:ident)+) => {
        $value.transpose()
    };
    ($value:expr,) => {
        Some($value)
    };
}

/// `impl_builtin_waveform_traits!($name, ...fields of the type of $value...)` implements the
/// [`super::BuiltinWaveformParameters`] trait for `$name<Concrete>` and the
/// [`super::PartialBuiltinWaveformParameters`] trait for `$name<Partial<Concrete>>`; the
/// implementations are trivial, but assume that the types have a `raw_iq_values_at_sample_rate`
/// method.
///
/// Note that for nongeneric types, both traits are simply implemented for `$name`; this is the only
/// reason we take the fields as a macro argument.
macro_rules! impl_builtin_waveform_traits {
    ($name:ident $(, $field:ident)*) => {
        impl BuiltinWaveformParameters for instantiated_waveform!(
            $name<Concrete>, $($field)*
        ) {
            #[inline(always)]
            fn iq_values_at_sample_rate(
                self,
                common: CommonBuiltinParameters<Concrete>,
                sample_rate: f64,
            ) -> Result<IqSamples<Complex64>, SamplingError> {
                self.raw_iq_values_at_sample_rate(common, sample_rate)
                    .map(IqSamplesFor::unwrap_total)
            }
        }

        impl PartialBuiltinWaveformParameters for instantiated_waveform!(
            $name<Partial<Concrete>>, $($field)*
        ) {
            type Concrete = instantiated_waveform!($name<Concrete>, $($field)*);

            #[inline(always)]
            fn concretize(self) -> Option<Self::Concrete> {
                transpose_if_generic_waveform!(self, $($field)*)
            }

            #[inline(always)]
            fn partial_iq_values_at_sample_rate(
                self,
                common: CommonBuiltinParameters<Partial<Concrete>>,
                sample_rate: f64,
            ) -> Result<IqSamplesOrPlaceholder, SamplingError> {
                self.raw_iq_values_at_sample_rate(common, sample_rate)
                    .map(IqSamplesFor::into_iq_samples_or_placeholder)
            }
        }
    };
}

/// This macro implements the [`super::partiality::ConcretizableWaveform`] trait for the partial and
/// concrete variants of this waveform.
macro_rules! impl_concretizable {
    ($name:ident) => {
        impl ConcretizableWaveform for $name<Partial<Concrete>> {
            #[inline(always)]
            fn concretize(self) -> Result<$name<Concrete>, ()> {
                self.transpose().ok_or(())
            }
        }

        impl ConcretizableWaveform for $name<Concrete> {
            #[inline(always)]
            fn concretize(self) -> Result<Self, Infallible> {
                Ok(self)
            }
        }
    };
}

/// Define a Python getter and setter for the given type and field.
///
/// Some notes:
///
/// 1. We have to define the getter all at once because using a macro in the return type fails to be
///    able to refer to `'py` for the purposes of the `#[pyo3::pymethods]` macro.
///
/// 2. We have to define the methods in consecutive `impl` blocks because otherwise we'd have to
///    define just the method with a macro, and you can't use macros inside `#[pyo3::pymethods]`
///    blocks.
///
/// Setters don't *need* the same treatment, since they don't need to refer to any lifetime
/// parameters, but we define them along with the getters for simplicity.
#[cfg(feature = "python")]
macro_rules! python_get_set {
    ($ty_name:ident, $field:ident, ConcreteReal) => {
        paste::paste! {
            #[cfg_attr(feature = "stubs", gen_stub_pymethods)]
            #[pyo3::pymethods]
            impl $ty_name {
                #[getter($field)]
                fn [<py_get_$field>](&self) -> f64 {
                    self.0.$field
                }

                #[setter($field)]
                fn [<py_set_$field>](&mut self, $field: f64) {
                    self.0.$field = $field;
                }
            }
        }
    };

    ($ty_name:ident, $field:ident, Real) => {
        python_get_set!($ty_name, $field, PyAny("_Real"));
    };

    ($ty_name:ident, $field:ident, Complex) => {
        python_get_set!($ty_name, $field, PyAny("_Complex"));
    };

    ($ty_name:ident, $field:ident, PyAny($type_name:literal)) => {
        paste::paste! {
            #[cfg_attr(not(feature = "stubs"), optipy::strip_pyo3(only_stubs))]
            #[cfg_attr(feature = "stubs", gen_stub_pymethods)]
            #[pyo3::pymethods]
            impl $ty_name {
                #[getter($field)]
                #[gen_stub(override_return_type(type_repr = $type_name))]
                fn [<py_get_$field>]<'py>(&self, py: Python<'py>) -> &Bound<'py, PyAny> {
                    self.0.$field.0.bind(py)
                }

                #[setter($field)]
                fn [<py_set_$field>](
                    &mut self,
                    #[gen_stub(override_type(type_repr = $type_name))]
                    $field: Py<PyAny>
                ) {
                    self.0.$field.0 = $field;
                }
            }
        }
    };
}

/// Clone this value if it's not a `ConcreteReal`, otherwise copy it.
#[cfg(feature = "python")]
macro_rules! maybe_clone_ref {
    ($field:expr, ConcreteReal, $py:ident) => {
        *$field
    };

    ($field:expr, Real, $py:ident) => {
        $field.clone_ref($py)
    };

    ($field:expr, Complex, $py:ident) => {
        $field.clone_ref($py)
    };
}

/// Compare this value using Python equality if it's not a `ConcreteReal`, otherwise use regular equality
#[cfg(feature = "python")]
macro_rules! python_field_eq {
    ($field:ident, ConcreteReal, $other:ident, $py:ident) => {
        *$field == $other.$field
    };

    ($field:ident, Real, $other:ident, $py:ident) => {
        $field.py_eq($py, &$other.$field)?
    };

    ($field:ident, Complex, $other:ident, $py:ident) => {
        $field.py_eq($py, &$other.$field)?
    };
}

/// Push the Python `repr` of this field onto `$output`
#[cfg(feature = "python")]
macro_rules! push_field_repr {
    ($output:ident, $field:expr, ConcreteReal, $py:ident) => {{
        use std::fmt::Write as _;
        write!(&mut $output, "{}", $field).unwrap(); // Writing to a string can't fail
    }};

    ($output:ident, $field:expr, Real, $py:ident) => {
        $output.push_str($field.0.bind($py).repr()?.to_str()?);
    };

    ($output:ident, $field:expr, Complex, $py:ident) => {
        $output.push_str($field.0.bind($py).repr()?.to_str()?);
    };
}

/// A token-muncher to associate the `Real` and `Complex` type names with the corresponding string
/// literal, so that the `define_python_waveform!` and
/// `add_python_waveform_convenience_constructor!` macros can use them to override type signatures.
#[cfg(feature = "python")]
macro_rules! define_python_interop {
    ($name:ident $({ $($field:ident: $ty:ident),+ })?) => {
        define_python_interop! {
            @parse
                $name
            |
                $({ $($field: $ty),+ })?
        }
    };

    (@parse
         $name:ident $({ $($pfield:ident: $pty:ident $(($pty_str:literal))?,)+ })?
     |
         $({})?
    ) => {
        define_python_waveform! {
            $name $({ $($pfield: $pty $(($pty_str))?),+ })?
        }
        add_python_waveform_convenience_constructor! {
            $name $({ $($pfield: $pty $(($pty_str))?),+ })?
        }
    };

    (@parse
         $name:ident $({ $($pfield:ident: $pty:ident $(($pty_str:literal))?,)+ })?
     |
         { $field1:ident: ConcreteReal $(, $field:ident: $ty:ident)* }
    ) => {
        define_python_interop! {
            @parse
                $name { $($($pfield: $pty $(($pty_str))?,)+)? $field1: ConcreteReal, }
            |
                { $($field: $ty),* }
        }
    };

    (@parse
         $name:ident $({ $($pfield:ident: $pty:ident $(($pty_str:literal))?,)+ })?
     |
         { $field1:ident: Real $(, $field:ident: $ty:ident)* }
    ) => {
        define_python_interop! {
            @parse
                $name { $($($pfield: $pty $(($pty_str))?,)+)? $field1: Real ("_Real"), }
            |
                { $($field: $ty),* }
        }
    };

    (@parse
         $name:ident $({ $($pfield:ident: $pty:ident $(($pty_str:literal))?,)+ })?
     |
         { $field1:ident: Complex $(, $field:ident: $ty:ident)* }
    ) => {
        define_python_interop! {
            @parse
                $name { $($($pfield: $pty $(($pty_str))?,)+)? $field1: Complex ("_Complex"), }
            |
                { $($field: $ty),* }
        }
    };
}

/// Generate the Python interface to this waveform.  See the module docs for the details of the API.
#[cfg(feature = "python")]
macro_rules! define_python_waveform {
    ($name:ident) => {
        // We can reuse the empty struct as the type that's exposed to Python, but even if we do we
        // still need to give it its methods.
        #[cfg_attr(not(feature = "stubs"), optipy::strip_pyo3(only_stubs))]
        #[cfg_attr(feature = "stubs", gen_stub_pymethods)]
        #[pyo3::pymethods]
        impl super::$name {
            #[new]
            fn __new__() -> Self {
                Self
            }

            #[pyo3(name = "iq_values_at_sample_rate")]
            fn py_iq_values_at_sample_rate<'py>(
                &self,
                py: Python<'py>,
                #[gen_stub(override_type(
                    type_repr = "CommonBuiltinParameters[builtins.float, __T]",
                    imports = ("builtins"))
                )]
                common: PyCommonBuiltinParameters,
                sample_rate: f64,
            ) -> PyResult<PyIqSamples> {
                Ok(self
                   .iq_values_at_sample_rate(
                       common
                           .0
                           .as_ref()
                           .try_evaluate(
                               |PyAnyRust(r)| r.extract(py),
                               |PyAnyRust(c)| c.extract(py),
                           )?,
                       sample_rate,
                   )?
                   .into())
            }

            pub(crate) fn __eq__<'py>(
                &self,
                #[gen_stub(override_type(type_repr = "builtins.object", imports = ("builtins")))]
                other: Bound<'py, PyAny>,
            ) -> PyResult<bool> {
                if let Some(Self) = py_cast_and_borrow(&other)?.as_deref() {
                    Ok(true)
                } else if let Some(super::quilpy::PyBuiltinWaveform(super::BuiltinWaveform::$name(
                    Self
                ))) = py_cast_and_borrow(&other)?.as_deref()
                {
                    Ok(true)
                } else {
                    Ok(false)
                }
            }

            pub(crate) fn __repr__(&self) -> &'static str {
                concat!(stringify!($name), "()")
            }
        }
    };

    ($name:ident { $($field:ident: $ty:ident $(($ty_str:literal))?),+ }) => {
        paste::paste! {
            #[derive(Clone, Debug)]
            #[cfg_attr(feature = "stubs", gen_stub_pyclass)]
            #[pyo3::pyclass(module = "quil._quil.waveform", generic, subclass, from_py_object)]
            pub struct $name(pub super::$name<Pythonic>);

            #[cfg_attr(not(feature = "stubs"), optipy::strip_pyo3(only_stubs))]
            #[cfg_attr(feature = "stubs", gen_stub_pymethods)]
            #[pyo3::pymethods]
            impl $name {
                #[pyo3(signature = (* $(, $field)+))]
                #[gen_stub(override_return_type(type_repr = "$SELF"))]
                #[new]
                fn __new__(
                    $(
                        $(#[gen_stub(override_type(type_repr = $ty_str))])?
                        $field: field_type!((<Pythonic as WaveformData>), $ty)
                    ),+
                ) -> Self {
                    Self(super::$name { $($field),+ })
                }

                fn __getnewargs_ex__<'py>(
                    &self,
                    py: Python<'py>
                ) -> PyResult<Bound<'py, PyTuple>> {
                    let Self(super::$name { $($field),+ }) = self;
                    let arguments: [(&'static str, Bound<'py, PyAny>); _] = [
                        $((
                            stringify!($field),
                            maybe_clone_ref!($field, $ty, py).into_bound_py_any(py)?,
                        )),+
                    ];
                    (PyTuple::empty(py), arguments.into_py_dict(py)?).into_pyobject(py)
                }

                #[pyo3(name = "iq_values_at_sample_rate")]
                fn py_iq_values_at_sample_rate<'py>(
                    &self,
                    py: Python<'py>,
                    #[gen_stub(override_type(
                        type_repr = "CommonBuiltinParameters[builtins.float, __T]",
                        imports = ("builtins"))
                    )]
                    common: PyCommonBuiltinParameters,
                    sample_rate: f64,
                ) -> PyResult<PyIqSamples> {
                    Ok(self
                       .0
                       .as_ref()
                       .try_evaluate::<crate::waveform::Concrete, _>(
                           |PyAnyRust(r)| r.extract(py),
                           |PyAnyRust(c)| c.extract(py),
                       )?
                       .iq_values_at_sample_rate(
                           common
                               .0
                               .as_ref()
                               .try_evaluate(
                                   |PyAnyRust(r)| r.extract(py),
                                   |PyAnyRust(c)| c.extract(py),
                               )?,
                           sample_rate,
                       )?
                       .into())
                }

                fn __eq__<'py>(
                    &self,
                    py: Python<'py>,
                    #[gen_stub(override_type(type_repr = "builtins.object", imports = ("builtins")))]
                    other: Bound<'py, PyAny>,
                ) -> PyResult<bool> {
                    self.0.py_eq(py, other)
                }

                fn __repr__<'py>(&self, py: Python<'py>) -> PyResult<String> {
                    self.0.py_repr(py)
                }
            }

            $(python_get_set!($name, $field, $ty);)*

            impl super::$name<Reference<'_, Pythonic>> {
                pub(crate) fn py_eq<'py>(
                    &self,
                    py: Python<'py>,
                    other: Bound<'py, PyAny>,
                ) -> PyResult<bool> {
                    if let Some($name(other)) = py_cast_and_borrow(&other)?.as_deref() {
                        self.py_eq_this_type(py, other)
                    } else if let Some(
                        super::quilpy::PyBuiltinWaveform(super::BuiltinWaveform::$name(other)
                    )) = py_cast_and_borrow(&other)?.as_deref()
                    {
                        self.py_eq_this_type(py, other)
                    } else {
                        Ok(false)
                    }
                }

                pub(crate) fn py_eq_this_type<'py>(
                    &self,
                    py: Python<'py>,
                    other: &super::$name<Pythonic>,
                ) -> PyResult<bool> {
                    let Self { $($field),+ } = self;
                    $(
                        if !python_field_eq!($field, $ty, other, py) {
                            return Ok(false);
                        }
                    )+
                    Ok(true)
                }
            }

            impl super::$name<Pythonic> {
                pub(crate) fn py_eq<'py>(
                    &self,
                    py: Python<'py>,
                    other: Bound<'py, PyAny>,
                ) -> PyResult<bool> {
                    self.as_ref().py_eq(py, other)
                }

                pub(crate) fn py_repr<'py>(&self, py: Python<'py>) -> PyResult<String> {
                    let Self { $($field),+ } = self;
                    let mut output = stringify!($name).to_owned();
                    let mut sep = "(";
                    $(
                        output.push_str(sep);
                        output.push_str(concat!(stringify!($field), "="));
                        push_field_repr!(output, $field, $ty, py);
                        #[allow(unused_assignments)]
                        { sep = ", "; }
                    )+
                    output.push(')');
                    Ok(output)
                }
            }
        }
    }
}

#[cfg(feature = "python")]
macro_rules! add_python_waveform_convenience_constructor {
    ($name:ident $({ $($field:ident: $ty:ident $(($ty_str:literal))?),+ })?) => {
        paste::paste! {
            #[cfg_attr(not(feature = "stubs"), optipy::strip_pyo3(only_stubs))]
            #[cfg_attr(feature = "stubs", gen_stub_pymethods)]
            #[pyo3::pymethods]
            impl crate::waveform::quilpy::PyWaveform {
                #[pyo3(
                    name = $name:snake,
                    signature = (
                        *,
                        duration, scale = None, phase = None, detuning = None,
                        $($($field),+)?
                    )
                )]
                #[gen_stub(override_return_type(type_repr = "$SELF"))]
                #[staticmethod]
                #[allow(
                    clippy::too_many_arguments,
                    reason = "a many-keyword-argument function is genuinely a nice interface"
                )]
                fn [<py_$name:snake>]<'py>(
                    py: Python<'py>,
                    duration: f64,
                    #[gen_stub(override_type(
                        type_repr = "typing.Optional[_Real]",
                        imports = ("typing"))
                    )]
                    scale: Option<&Bound<'py, PyAny>>,
                    #[gen_stub(override_type(
                        type_repr = "typing.Optional[_Real]",
                        imports = ("typing"))
                    )]
                    phase: Option<&Bound<'py, PyAny>>,
                    #[gen_stub(override_type(
                        type_repr = "typing.Optional[_Real]",
                        imports = ("typing"))
                    )]
                    detuning: Option<&Bound<'py, PyAny>>,
                    $($(
                        $(#[gen_stub(override_type(type_repr = $ty_str))])?
                        $field: field_type!((<Pythonic as WaveformData>), $ty)
                    ),+)?
                ) -> Self {
                    Self(crate::waveform::Waveform::Builtin {
                        common_parameters: super::CommonBuiltinParameters {
                            duration,
                            scale: scale.map(|scale| {
                                PyAnyRust(scale.as_unbound().clone_ref(py))
                            }),
                            phase: phase.map(|phase| {
                                Cycles(PyAnyRust(phase.as_unbound().clone_ref(py)))
                            }),
                            detuning: detuning.map(|detuning| {
                                PyAnyRust(detuning.as_unbound().clone_ref(py))
                            }),
                        },
                        waveform: super::BuiltinWaveform::$name(super::$name $({
                            $($field),+
                        })?),
                    })
                }
            }
        }
    }
}

/// Export one of the Python waveform wrappers under its `Py$waveform` name, if necessary.
#[cfg(feature = "python")]
macro_rules! reexport_python_waveform {
    ($submodule:ident::$name:ident as $py_name:ident) => {};

    ($submodule:ident::$name:ident { $($field:ident: $ty:ident),+ } as $py_name:ident) => {
        pub use $submodule::$name as $py_name;
    };
}

/// Define a single waveform, as described in the introduction to this section.  Note that we handle
/// fieldless waveforms specially; these get to omit a lot of work because they aren't generic.
/// Documentation is handled in `define_waveforms!`.
macro_rules! define_waveform {
    {
        $(#[$struct_meta:meta])*
        pub struct $name:ident
    } => {
        $(#[$struct_meta])*
        #[derive(Clone, PartialEq, Debug, Copy, Serialize, Deserialize)]
        #[cfg_attr(feature = "stubs", gen_stub_pyclass)]
        #[cfg_attr(feature = "python", pyo3::pyclass(module = "quil._quil.waveform", subclass, from_py_object))]
        pub struct $name;

        #[automatically_derived]
        impl<T: WaveformData> parse::Extractable<T> for $name {
            fn extract_from<P: GeneralWaveformParameters, EF64, ER, EC>(
                parameters: &mut P,
                _concrete_real: impl FnMut(P::Value) -> Result<f64, EF64>,
                _real: impl FnMut(P::Value) -> Result<T::Real, ER>,
                _complex: impl FnMut(P::Value) -> Result<T::Complex, EC>,
            ) -> Result<Self, GeneralWaveformParameterError<EF64, ER, EC>> {
                Ok(Self)
            }
        }

        impl_builtin_waveform_traits!($name);
    };

    {
        $(#[$struct_meta:meta])*
        pub struct $name:ident {
            $(
                $(#[$field_meta:meta])*
                pub $field:ident: $ty:ident
            ),+
            $(,)?
        }
    } => {
        $(#[$struct_meta])*
        #[derive_where(Clone, PartialEq, Debug)]
        #[derive_where(
            Copy, Serialize, Deserialize;
            extract_type_if_generic_field!(Real; $($ty),+),
            extract_type_if_generic_field!(Complex; $($ty),+)
        )]
        pub struct $name<T: WaveformData> {
            $(
                $(#[$field_meta])*
                pub $field: field_type!(T, $ty)
            ),+
        }

        #[automatically_derived]
        impl<T: WaveformData> parse::Extractable<T> for $name<T> {
            #[allow(
                unused_variables, unused_mut,
                reason = "macro-generated code; not all waveforms have all three kinds of \
                          parameters"
            )]
            fn extract_from<P: GeneralWaveformParameters, EF64, ER, EC>(
                parameters: &mut P,
                mut concrete_real: impl FnMut(P::Value) -> Result<f64, EF64>,
                mut real: impl FnMut(P::Value) -> Result<T::Real, ER>,
                mut complex: impl FnMut(P::Value) -> Result<T::Complex, EC>,
            ) -> Result<Self, GeneralWaveformParameterError<EF64, ER, EC>> {
                paste::paste! {
                    $(
                        let $field = parse::mandatory(
                            parameters,
                            stringify!($field),
                            &mut [<$ty:snake>],
                            GeneralWaveformParameterError::[<Bad$ty>],
                        )?;
                    )+
                }
                Ok(Self { $($field),+ })
            }
        }

        impl<S: WaveformData> $name<S> {
            #[doc = concat!(
                "Convert an owned [`", stringify!($name), "`] into an equivalent one ",
                "whose (non-concrete) parameters are all references."
            )]
            pub fn as_ref(&self) -> $name<Reference<'_, S>> {
                let Self { $($field),+ } = self;
                $name {
                    $($field: field_referencer!($ty, $field)),+
                }
            }

            #[doc = concat!(
                "Convert one [`", stringify!($name), "`] into another ",
                "by replacing its associated data."
            )]
            /// Given two forms of waveform data, `S` and `T`, the user specifies how to evaluate
            /// `S`'s real numbers into `T`'s real numbers and how to evaluate `S`'s complex numbers
            /// to `T`'s complex numbers.  For example, to convert parsed
            /// ([`Syntactic`][crate::waveform::Syntactic]) parameters into sampleable
            /// ([`Concrete`]) parameters, you can pass
            /// [`Expression::evaluate`][crate::expression::Expression::evaluate] to this function.
            ///
            /// For a more detailed example, see the documentation for
            /// [`Waveform::try_evaluate`][crate::waveform::Waveform::try_evaluate], which has the
            /// same structure as this function.
            #[allow(unused_variables, reason = "macro-generated code")]
            pub fn try_evaluate<T: WaveformData, E>(
                self,
                real: impl Fn(S::Real) -> Result<T::Real, E>,
                complex: impl Fn(S::Complex) -> Result<T::Complex, E>,
            ) -> Result<$name<T>, E> {
                let Self { $($field),+ } = self;
                Ok($name {
                    $($field: field_evaluator!($ty, real = real, complex = complex, $field)),+
                })
            }
        }

        impl<T: WaveformData> $name<Partial<T>> {
            #[doc = concat!(
                "Returns `None` if any of the partial [`", stringify!($name),
                "`]'s data is missing, and returns its underlying total form, [`",
                stringify!($name), "<T>`], otherwise."
            )]
            pub fn transpose(self) -> Option<$name<T>> {
                let Self { $($field),+ } = self;
                Some($name {
                    $($field: field_transposer!($field, $ty)),+
                })
            }
        }

        impl<S: WaveformData> super::higher_kinded::WaveformParameters for $name<S> {
            type WaveformData = S;

            type WithWaveformData<T: WaveformData> = $name<T>;

            #[inline(always)]
            fn as_ref(&self) -> Self::WithWaveformData<Reference<'_, Self::WaveformData>> {
                self.as_ref()
            }

            #[inline(always)]
            fn try_evaluate<T: WaveformData, E>(
                self,
                real:
                    impl Fn(<Self::WaveformData as WaveformData>::Real) -> Result<T::Real, E>,
                complex:
                    impl Fn(<Self::WaveformData as WaveformData>::Complex) -> Result<T::Complex, E>,
            ) -> Result<Self::WithWaveformData<T>, E> {
                self.try_evaluate(real, complex)
            }
        }

        impl<T: WaveformData>
            super::higher_kinded::PartialWaveformParameters for $name<Partial<T>>
        {
            type TotalWaveformData = T;

            #[inline(always)]
            fn transpose(self) -> Option<Self::WithWaveformData<Self::TotalWaveformData>> {
                self.transpose()
            }
        }

        impl_builtin_waveform_traits!($name, $($field),+);
        impl_concretizable!($name);
   }
}

/// Define a collection of waveforms, as described in the introduction to this section.  Also
/// generates Python wrappers in a submodule and creates the `Sealed` trait used for
/// [`super::BuiltinWaveformParameters`].
///
/// NOTE: To validate our Python interop, `quil-rs/scripts/lint-quil-rs.py` needs to be able to
/// process the contents of `define_waveform!`.  Please edit the `_define_waveform` method in that
/// file to keep it in sync with changes to the input format of this macro.
macro_rules! define_waveforms {
    (
        $(
            $(#[doc = $struct_doc:literal])*
            #[waveform_source($waveform_source:ident)]
            $(#[$struct_meta:meta])*
            pub struct $name:ident $({
                $(
                    $(#[$field_meta:meta])*
                    pub $field:ident: $ty:ident
                ),+
                $(,)?
            })?
            $(;)?
        )+
    ) => {
        $(
            define_waveform! {
                $(#[doc = $struct_doc])*
                ///
                #[doc = waveform_source!($waveform_source)]
                $(#[$struct_meta])*
                pub struct $name $({
                    $(
                        $(#[$field_meta])*
                        pub $field: $ty
                    ),+
                })?
            }
        )+

        // Exported from the `quilpy` submodule
        #[cfg(feature = "python")]
        mod quilpy_waveforms {
            use super::*;

            // We reexport the Python waveforms from this submodule so we can give them
            // `Py`-prefixed names; we can't do that directly because then we'd have to rename them,
            // and we can only rename them to string literals which aren't available inside this
            // macro.
            mod waveform_types {
                use super::macros::*;

                #[cfg(feature = "stubs")]
                use pyo3_stub_gen::derive::{gen_stub_pyclass, gen_stub_pymethods};

                use pyo3::{
                    marker::Python,
                    types::{
                        IntoPyDict as _, PyAny, PyAnyMethods as _, PyStringMethods as _, PyTuple,
                    },
                    Bound, IntoPyObject as _, IntoPyObjectExt as _, Py, PyResult,
                };

                use crate::{
                    quilpy::py_cast_and_borrow,
                    waveform::{
                        quilpy::{PyAnyRust, Pythonic},
                        sampling::quilpy::PyIqSamples,
                        Reference, WaveformData,
                    },
                    units::Cycles,
                };

                use super::{
                    quilpy::PyCommonBuiltinParameters,
                    BuiltinWaveformParameters as _,
                };

                $(define_python_interop!($name $({ $($field: $ty),+ })?);)*
            }

            paste::paste! {
                $(reexport_python_waveform! {
                    waveform_types::$name $({ $($field: $ty),+ })? as [<Py$name>]
                })*
            }
        }

        mod private {
            use super::macros::*;

            pub trait SealedConcrete {}
            impl SealedConcrete for super::BuiltinWaveform<super::Concrete> {}
            $(
                #[automatically_derived]
                impl SealedConcrete for instantiated_waveform!(
                    super::$name<super::Concrete>, $($($field)+)?
                ) {}
            )*

            pub trait SealedPartial {}
            impl SealedPartial for super::BuiltinWaveform<super::Partial<super::Concrete>> {}
            $(
                #[automatically_derived]
                impl SealedPartial for instantiated_waveform!(
                    super::$name<super::Partial<super::Concrete>>, $($($field)+)?
                ) {}
            )*
        }
    }
}

#[cfg(feature = "python")]
pub(crate) use {
    add_python_waveform_convenience_constructor, define_python_interop, define_python_waveform,
    maybe_clone_ref, push_field_repr, python_field_eq, python_get_set, reexport_python_waveform,
};

pub(crate) use {
    define_waveform, define_waveforms, extract_type_if_generic_field, field_evaluator,
    field_referencer, field_transposer, field_type, impl_builtin_waveform_traits,
    impl_concretizable, instantiated_waveform, transpose_if_generic_waveform, waveform_source,
};