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
// Copyright © 2021-2023 HQS Quantum Simulations GmbH. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing permissions and
// limitations under the License.

use crate::{extract_fields_with_types, RESERVED_FIELDS};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use std::collections::HashSet;
use syn::{Data, DataStruct, DeriveInput, Ident};

/// Dispatch to derive Operate for enums and structs

pub fn dispatch_struct(input: DeriveInput) -> TokenStream {
    let ident = input.ident;
    match input.data {
        Data::Struct(ds) => operate_struct(ds, ident),
        _ => panic!("InvolveQubits can only be derived on structs"),
    }
}

/// Generate TokenStream of implementation of Operate for structs
fn operate_struct(ds: DataStruct, ident: Ident) -> TokenStream {
    let reserved_fields: HashSet<&str> = RESERVED_FIELDS.iter().cloned().collect();
    let fields_with_type = extract_fields_with_types(ds).into_iter();
    let input_arguments = fields_with_type
        .clone()
        .map(|(id, type_string, ty)| match type_string {
            Some(s) => match s.as_str() {
                "CalculatorFloat" => quote! {#id: &pyo3::PyAny},
                "Circuit" => quote! {#id: &pyo3::PyAny},
                "Option<Circuit>" => quote! {#id: &pyo3::PyAny},
                _ => quote! {#id: #ty},
            },
            _ => quote! {#id: #ty},
        });
    let arguments = fields_with_type
        .clone()
        .map(|(id, type_string, _)| match type_string {
            Some(s) => match s.as_str() {
                "CalculatorFloat" => {
                    let id_extracted = format_ident!("{}_extracted", id);
                    quote! {
                    #id_extracted}
                }
                "Circuit" => {
                    let id_extracted = format_ident!("{}_extracted", id);
                    quote! {
                    #id_extracted}
                }
                "Option<Circuit>" => {
                    let id_extracted = format_ident!("{}_extracted", id);
                    quote! {
                    #id_extracted}
                }
                _ => {
                    quote! {#id}
                }
            },
            _ => {
                quote! {#id}
            }
        });
    let conversion_quotes = fields_with_type
        .clone()
        .map(|(id, type_string, ty)| match type_string{
            Some(s) => match s.as_str() {
            "CalculatorFloat" => {
                let id_extracted = format_ident!("{}_extracted", id);
                quote! {
                    let #id_extracted: #ty = convert_into_calculator_float(#id).map_err(|x| {
                        pyo3::exceptions::PyTypeError::new_err(format!("Argument cannot be converted to CalculatorFloat {:?}",x))
                    })?;
                }
            },
            "Circuit" => {
                let id_extracted = format_ident!("{}_extracted", id);
                quote! {
                    let #id_extracted: #ty = convert_into_circuit(#id).map_err(|x| {
                        pyo3::exceptions::PyTypeError::new_err(format!("Argument cannot be converted to Circuit {:?}",x))
                    })?;
                }
            },
            "Option<Circuit>" => {
                let id_extracted = format_ident!("{}_extracted", id);
                quote! {
                    let tmp: Option<&PyAny> = #id.extract().map_err(|x| {
                        pyo3::exceptions::PyTypeError::new_err(format!("Argument cannot be converted to Circuit {:?}",x))
                    })?;
                    let #id_extracted: Option<Circuit> = match tmp{
                        Some(cw) => Some(convert_into_circuit(cw).map_err(|x| {
                            pyo3::exceptions::PyTypeError::new_err(format!("Argument cannot be converted to Circuit {:?}",x))
                    })?),
                        _ => None };
            }},
            _ => {
                quote! {}
            }
        },
        _ => {
            quote! {}
        }
        });
    let getter_fields = fields_with_type
        .filter(|(id, _, _)| !reserved_fields.contains(id.to_string().as_str()))
        .map(|(id, type_string, ty)| match type_string {
            Some(s) => match s.as_str() {
                "CalculatorFloat" => {
                    let msg = format!("Returns value of attribute {}", id);
                    quote! {
                        #[doc = #msg]
                        pub fn #id(&self) -> CalculatorFloatWrapper{
                            CalculatorFloatWrapper{internal: self.internal.#id().clone()}
                        }
                    }
                }
                "Circuit" => {
                    let msg = format!("Get value of struct field {}", id);
                    quote! {
                        #[doc = #msg]
                        pub fn #id(&self) -> CircuitWrapper{
                            CircuitWrapper{internal: self.internal.#id().clone()}
                        }
                    }
                }
                "Option<Circuit>" => {
                    let msg = format!("Get value of struct field {}", id);
                    quote! {
                            #[doc = #msg]
                            pub fn #id(&self) -> Option<CircuitWrapper>{
                                match self.internal.#id().as_ref(){
                                    None => None,
                                    Some(x) => Some(CircuitWrapper{internal: x.clone()})
                            }
                        }
                    }
                }
                _ => {
                    let msg = format!("Get value of struct field {}", id);
                    quote! {
                        #[doc = #msg]
                        pub fn #id(&self) -> #ty{
                            self.internal.#id().clone()
                        }
                    }
                }
            },
            _ => {
                let msg = format!("Get value of struct field {}", id);
                quote! {
                    #[doc=#msg]
                    pub fn #id(&self) -> #ty{
                        self.internal.#id().clone()
                    }
                }
            }
        });

    let new_msg = format!("Creates new instance of Operations {}", ident);
    quote! {

        #(#getter_fields)*

        #[new]
        #[doc = #new_msg]
        fn new(#(#input_arguments),*) -> PyResult<Self>{
            #(#conversion_quotes)*
            Ok(Self{internal: #ident::new(#(#arguments),*)})
        }

        /// Returns true if operation contains symbolic parameters
        ///
        /// Returns:
        ///     bool
        fn is_parametrized(&self) -> bool {
                self.internal.is_parametrized()
        }

        /// Returns tags identifying the Operation
        ///
        /// Returns:
        ///     list[str]: The tags identifying the operation
        fn tags(&self) -> Vec<String>{
            self.internal.tags().iter().map(|s| s.to_string()).collect()
        }

        /// Returns hqslang name of Operation
        ///
        /// Returns:
        ///     str: The name
        fn hqslang(&self) -> &'static str{
            self.internal.hqslang()
        }

        /// Substitutes internal symbolic parameters with float values
        ///
        /// Only available when all symbolic expressions can be evaluated to float with the
        /// provided parameters.
        ///
        /// Args:
        ///     substitution_parameters (dict[str, float]): The substituted free parameters
        ///
        /// Returns:
        ///     Operation: The operation with the parameters substituted
        ///
        /// Raises:
        ///     RuntimeError: Parameter Substitution failed
        fn substitute_parameters(&self, substitution_parameters: std::collections::HashMap<&str, f64>) -> PyResult<Self> {
            let mut calculator = qoqo_calculator::Calculator::new();
            for (key, val) in substitution_parameters.iter(){
                calculator.set_variable(key, *val);
            }
            Ok(Self{internal: self.internal.substitute_parameters(&calculator).map_err(|x| {
                pyo3::exceptions::PyRuntimeError::new_err(format!("Parameter Substitution failed: {:?}", x))
            })?})
        }

        /// Remap qubits
        ///
        /// Args:
        ///     mapping (dict[int, int]): The mapping
        ///
        /// Returns:
        ///     Operation: The operation with the remapped qubits
        ///
        /// Raises:
        ///     RuntimeError: Qubit remapping failed
        fn remap_qubits(&self, mapping: HashMap<usize, usize>) -> PyResult<Self>{
            let new_internal = self.internal.remap_qubits(&mapping).map_err(|x|
                PyRuntimeError::new_err(format!("Qubit remapping failed: {:?}",x))
            )?;
            Ok(Self{internal: new_internal})
        }

        /// List all involved Qubits
        ///
        /// Returns:
        ///     Union[set[int], str]: The involved qubits as a set or 'ALL' if all qubits are involved
        fn involved_qubits(&self) -> PyObject {
            Python::with_gil(|py| -> PyObject {
                let involved = self.internal.involved_qubits();
                match involved {
                    InvolvedQubits::All => {
                        let pyref: &PySet = PySet::new(py, &["All"]).unwrap();
                        let pyobject: PyObject = pyref.to_object(py);
                        pyobject
                    },
                    InvolvedQubits::None => {
                        let pyref: &PySet = PySet::empty(py).unwrap();
                        let pyobject: PyObject = pyref.to_object(py);
                        pyobject
                    },
                    InvolvedQubits::Set(x) => {
                        let mut vector: Vec<usize> = Vec::new();
                        for qubit in x {
                            vector.push(qubit)
                        }
                        let pyref: &PySet = PySet::new(py, &vector[..]).unwrap();
                        let pyobject: PyObject = pyref.to_object(py);
                        pyobject
                    },
                }
            })
        }

        /// Copies Operation
        ///
        /// For qoqo operations copy is always a deep copy
        fn __copy__(&self) -> Self {
            self.clone()
        }

        /// Creates deep copy of Operation
        fn __deepcopy__(&self, _memodict: Py<PyAny>) -> Self {
            self.clone()
        }
    }
}