• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Qiskit / qiskit / 10559942977

26 Aug 2024 12:41PM UTC coverage: 89.208% (-0.01%) from 89.22%
10559942977

push

github

web-flow
Bump pypa/cibuildwheel from 2.19.2 to 2.20.0 in the github_actions group (#12905)

Bumps the github_actions group with 1 update: [pypa/cibuildwheel](https://github.com/pypa/cibuildwheel).


Updates `pypa/cibuildwheel` from 2.19.2 to 2.20.0
- [Release notes](https://github.com/pypa/cibuildwheel/releases)
- [Changelog](https://github.com/pypa/cibuildwheel/blob/main/docs/changelog.md)
- [Commits](https://github.com/pypa/cibuildwheel/compare/v2.19.2...v2.20.0)

---
updated-dependencies:
- dependency-name: pypa/cibuildwheel
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github_actions
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

71624 of 80289 relevant lines covered (89.21%)

398758.7 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.69
/crates/qasm2/src/parse.rs
1
// This code is part of Qiskit.
2
//
3
// (C) Copyright IBM 2023
4
//
5
// This code is licensed under the Apache License, Version 2.0. You may
6
// obtain a copy of this license in the LICENSE.txt file in the root directory
7
// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
8
//
9
// Any modifications or derivative works of this code must retain this
10
// copyright notice, and modified files need to carry a notice indicating
11
// that they have been altered from the originals.
12

13
//! The core of the parsing algorithm.  This module contains the core logic for the
14
//! recursive-descent parser, which handles all statements of OpenQASM 2.  In places where we have
15
//! to evaluate a mathematical expression on parameters, we instead swap to a short-lived
16
//! operator-precedence parser.
17

18
use hashbrown::{HashMap, HashSet};
19
use num_bigint::BigUint;
20
use pyo3::prelude::{PyObject, PyResult, Python};
21

22
use crate::bytecode::InternalBytecode;
23
use crate::error::{
24
    message_bad_eof, message_generic, message_incorrect_requirement, Position, QASM2ParseError,
25
};
26
use crate::expr::{Expr, ExprParser};
27
use crate::lex::{Token, TokenContext, TokenStream, TokenType, Version};
28
use crate::{CustomClassical, CustomInstruction};
29

30
/// The number of gates that are built in to the OpenQASM 2 language.  This is U and CX.
31
const N_BUILTIN_GATES: usize = 2;
32
/// The "qelib1.inc" special include.  The elements of the tuple are the gate name, the number of
33
/// parameters it takes, and the number of qubits it acts on.
34
const QELIB1: [(&str, usize, usize); 23] = [
35
    ("u3", 3, 1),
36
    ("u2", 2, 1),
37
    ("u1", 1, 1),
38
    ("cx", 0, 2),
39
    ("id", 0, 1),
40
    ("x", 0, 1),
41
    ("y", 0, 1),
42
    ("z", 0, 1),
43
    ("h", 0, 1),
44
    ("s", 0, 1),
45
    ("sdg", 0, 1),
46
    ("t", 0, 1),
47
    ("tdg", 0, 1),
48
    ("rx", 1, 1),
49
    ("ry", 1, 1),
50
    ("rz", 1, 1),
51
    ("cz", 0, 2),
52
    ("cy", 0, 2),
53
    ("ch", 0, 2),
54
    ("ccx", 0, 3),
55
    ("crz", 1, 2),
56
    ("cu1", 1, 2),
57
    ("cu3", 3, 2),
58
];
59

60
const BUILTIN_CLASSICAL: [&str; 6] = ["cos", "exp", "ln", "sin", "sqrt", "tan"];
61

62
/// Define a simple newtype that just has a single non-public `usize` field, has a `new`
63
/// constructor, and implements `Copy` and `IntoPy`.  The first argument is the name of the type,
64
/// the second is whether to also define addition to make offsetting the newtype easier.
65
macro_rules! newtype_id {
66
    ($id:ident, false) => {
67
        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
68
        pub struct $id(usize);
69

70
        impl $id {
71
            pub fn new(value: usize) -> Self {
27,980✔
72
                Self(value)
27,980✔
73
            }
27,980✔
74
        }
75

76
        impl pyo3::IntoPy<PyObject> for $id {
77
            fn into_py(self, py: Python<'_>) -> PyObject {
8,388✔
78
                self.0.into_py(py)
8,388✔
79
            }
8,388✔
80
        }
81
    };
82

83
    ($id:ident, true) => {
84
        newtype_id!($id, false);
85

86
        impl std::ops::Add<usize> for $id {
87
            type Output = Self;
88

89
            fn add(self, rhs: usize) -> Self {
5,912✔
90
                Self::new(self.0 + rhs)
5,912✔
91
            }
5,912✔
92
        }
93
    };
94
}
95

96
newtype_id!(GateId, false);
97
newtype_id!(CregId, false);
98
newtype_id!(ParamId, false);
99
newtype_id!(QubitId, true);
100
newtype_id!(ClbitId, true);
101

102
/// A symbol in the global symbol table.  Parameters and individual qubits can't be in the global
103
/// symbol table, as there is no way for them to be defined.
104
pub enum GlobalSymbol {
105
    Qreg {
106
        size: usize,
107
        start: QubitId,
108
    },
109
    Creg {
110
        size: usize,
111
        start: ClbitId,
112
        index: CregId,
113
    },
114
    Gate {
115
        num_params: usize,
116
        num_qubits: usize,
117
        index: GateId,
118
    },
119
    Classical {
120
        callable: PyObject,
121
        num_params: usize,
122
    },
123
}
124

125
impl GlobalSymbol {
126
    pub fn describe(&self) -> &'static str {
42✔
127
        match self {
42✔
128
            Self::Qreg { .. } => "a quantum register",
10✔
129
            Self::Creg { .. } => "a classical register",
12✔
130
            Self::Gate { .. } => "a gate",
14✔
131
            Self::Classical { .. } => "a custom classical function",
6✔
132
        }
133
    }
42✔
134
}
135

136
/// Information about a gate that permits a new definition in the OQ3 file only in the case that
137
/// the number of parameters and qubits matches.  This is used when the user specifies custom gates
138
/// that are not
139
struct OverridableGate {
140
    num_params: usize,
141
    num_qubits: usize,
142
    index: GateId,
143
}
144

145
impl From<OverridableGate> for GlobalSymbol {
146
    fn from(value: OverridableGate) -> Self {
3,676✔
147
        Self::Gate {
3,676✔
148
            num_params: value.num_params,
3,676✔
149
            num_qubits: value.num_qubits,
3,676✔
150
            index: value.index,
3,676✔
151
        }
3,676✔
152
    }
3,676✔
153
}
154

155
/// A symbol in the scope of a single gate definition.  This only includes the symbols that are
156
/// specifically gate-scoped.  The rest are part of [GlobalSymbol].
157
pub enum GateSymbol {
158
    Qubit { index: QubitId },
159
    Parameter { index: ParamId },
160
}
161

162
impl GateSymbol {
163
    pub fn describe(&self) -> &'static str {
6✔
164
        match self {
6✔
165
            Self::Qubit { .. } => "a qubit",
2✔
166
            Self::Parameter { .. } => "a parameter",
4✔
167
        }
168
    }
6✔
169
}
170

171
/// An operand for an instruction.  This can be both quantum or classical.  Classical operands only
172
/// occur in the `measure` operation.  `Single` variants are what we mostly expect to see; these
173
/// happen in gate definitions (always), and in regular applications when registers are indexed.
174
/// The `Range` operand only occurs when a register is used as an operation target.
175
enum Operand<T> {
176
    Single(T),
177
    Range(usize, T),
178
}
179

180
/// The available types for the arrays of parameters in a gate call.  The `Constant` variant is for
181
/// general applications, whereas the more general `Expression` variant is for gate bodies, where
182
/// there might be mathematics occurring on symbolic parameters.  We have the special case for the
183
/// far more common `Constant` form; in this case we immediately unwrap the result of the
184
/// `ExprParser`, and we won't have to make a new vector with the conversion later.
185
enum GateParameters {
186
    Constant(Vec<f64>),
187
    Expression(Vec<Expr>),
188
}
189

190
/// An equality condition from an `if` statement.  These can condition gate applications, measures
191
/// and resets, although in practice they're basically only ever used on gates.
192
#[derive(Clone)]
193
struct Condition {
194
    creg: CregId,
195
    value: BigUint,
196
}
197

198
/// Find the first match for the partial [filename] in the directories along [path].  Returns
199
/// `None` if the cannot be found.
200
fn find_include_path(
20✔
201
    filename: &std::path::Path,
20✔
202
    path: &[std::path::PathBuf],
20✔
203
) -> Option<std::path::PathBuf> {
20✔
204
    for directory in path.iter() {
24✔
205
        let mut absolute_path = directory.clone();
24✔
206
        absolute_path.push(filename);
24✔
207
        if absolute_path.is_file() {
24✔
208
            return Some(absolute_path);
18✔
209
        }
6✔
210
    }
211
    None
2✔
212
}
20✔
213

214
/// The state of the parser (but not its output).  This struct is opaque to the rest of the
215
/// program; only its associated functions ever need to modify its internals.  The counts of
216
/// qubits, clbits, classical registers and gates are necessary to efficiently assign index keys to
217
/// new symbols as they arise.  We don't need to track quantum registers like this because no part
218
/// of the output instruction set requires a reference to a quantum register, since we resolve any
219
/// broadcast gate applications from within Rust.
220
pub struct State {
221
    tokens: Vec<TokenStream>,
222
    /// The context object that owns all the text strings that back the tokens seen so far.  This
223
    /// needs to be given as a read-only reference to the [Token] methods that extract information
224
    /// based on the text they came from.
225
    context: TokenContext,
226
    include_path: Vec<std::path::PathBuf>,
227
    /// Mapping of name to global-scoped symbols.
228
    symbols: HashMap<String, GlobalSymbol>,
229
    /// Mapping of name to gate-scoped symbols.  This object only logically lasts for the duration
230
    /// of the parsing of one gate definition, but we can save allocations by re-using the same
231
    /// object between calls.
232
    gate_symbols: HashMap<String, GateSymbol>,
233
    /// Gate names that can accept a definition, even if they are already in the symbol table as
234
    /// gates. For example, if a user defines a custom gate as a `builtin`, we don't error out if
235
    /// we see a compatible definition later.  Regardless of whether the symbol was already in the
236
    /// symbol table or not, any gate-based definition of this symbol must match the signature we
237
    /// expect for it.
238
    overridable_gates: HashMap<String, OverridableGate>,
239
    num_qubits: usize,
240
    num_clbits: usize,
241
    num_cregs: usize,
242
    num_gates: usize,
243
    /// Whether a version statement is allowed in this position.
244
    allow_version: bool,
245
    /// Whether we're in strict mode or (the default) more permissive parse.
246
    strict: bool,
247
}
248

249
impl State {
250
    /// Create and initialise a state for the parser.
251
    pub fn new(
1,292✔
252
        tokens: TokenStream,
1,292✔
253
        include_path: Vec<std::path::PathBuf>,
1,292✔
254
        custom_instructions: &[CustomInstruction],
1,292✔
255
        custom_classical: &[CustomClassical],
1,292✔
256
        strict: bool,
1,292✔
257
    ) -> PyResult<Self> {
1,292✔
258
        let mut state = State {
1,292✔
259
            tokens: vec![tokens],
1,292✔
260
            context: TokenContext::new(),
1,292✔
261
            include_path,
1,292✔
262
            // For Qiskit-created circuits, all files will have the builtin gates and `qelib1.inc`,
1,292✔
263
            // so we allocate with that in mind.  There may well be overlap between libraries and
1,292✔
264
            // custom instructions, but this is small-potatoes allocation and we'd rather not have
1,292✔
265
            // to reallocate.
1,292✔
266
            symbols: HashMap::with_capacity(
1,292✔
267
                N_BUILTIN_GATES + QELIB1.len() + custom_instructions.len() + custom_classical.len(),
1,292✔
268
            ),
1,292✔
269
            gate_symbols: HashMap::new(),
1,292✔
270
            overridable_gates: HashMap::new(),
1,292✔
271
            num_qubits: 0,
1,292✔
272
            num_clbits: 0,
1,292✔
273
            num_cregs: 0,
1,292✔
274
            num_gates: 0,
1,292✔
275
            allow_version: true,
1,292✔
276
            strict,
1,292✔
277
        };
1,292✔
278
        for inst in custom_instructions {
8,844✔
279
            if state.symbols.contains_key(&inst.name)
7,554✔
280
                || state.overridable_gates.contains_key(&inst.name)
7,554✔
281
            {
282
                return Err(QASM2ParseError::new_err(message_generic(
2✔
283
                    None,
2✔
284
                    &format!("duplicate custom instruction '{}'", inst.name),
2✔
285
                )));
2✔
286
            }
7,552✔
287
            state.overridable_gates.insert(
7,552✔
288
                inst.name.clone(),
7,552✔
289
                OverridableGate {
7,552✔
290
                    num_params: inst.num_params,
7,552✔
291
                    num_qubits: inst.num_qubits,
7,552✔
292
                    index: GateId::new(state.num_gates),
7,552✔
293
                },
7,552✔
294
            );
7,552✔
295
            if inst.builtin {
7,552✔
296
                state.symbols.insert(
3,342✔
297
                    inst.name.clone(),
3,342✔
298
                    GlobalSymbol::Gate {
3,342✔
299
                        num_params: inst.num_params,
3,342✔
300
                        num_qubits: inst.num_qubits,
3,342✔
301
                        index: GateId::new(state.num_gates),
3,342✔
302
                    },
3,342✔
303
                );
3,342✔
304
            }
4,210✔
305
            state.num_gates += 1;
7,552✔
306
        }
307
        state.define_gate(None, "U".to_owned(), 3, 1)?;
1,290✔
308
        state.define_gate(None, "CX".to_owned(), 0, 2)?;
1,288✔
309
        for classical in custom_classical {
1,806✔
310
            if BUILTIN_CLASSICAL.contains(&&*classical.name) {
538✔
311
                return Err(QASM2ParseError::new_err(message_generic(
12✔
312
                    None,
12✔
313
                    &format!(
12✔
314
                        "cannot override builtin classical function '{}'",
12✔
315
                        &classical.name
12✔
316
                    ),
12✔
317
                )));
12✔
318
            }
526✔
319
            match state.symbols.insert(
526✔
320
                classical.name.clone(),
526✔
321
                GlobalSymbol::Classical {
526✔
322
                    num_params: classical.num_params,
526✔
323
                    callable: classical.callable.clone(),
526✔
324
                },
526✔
325
            ) {
526✔
326
                Some(GlobalSymbol::Gate { .. }) => {
327
                    let message = match classical.name.as_str() {
4✔
328
                        "U" | "CX" => format!(
4✔
329
                            "custom classical instructions cannot shadow built-in gates, but got '{}'",
2✔
330
                            &classical.name,
2✔
331
                        ),
2✔
332
                        _ => format!(
2✔
333
                            "custom classical instruction '{}' has a naming clash with a custom gate",
2✔
334
                            &classical.name,
2✔
335
                        ),
2✔
336
                    };
337
                    return Err(QASM2ParseError::new_err(message_generic(None, &message)));
4✔
338
                }
339
                Some(GlobalSymbol::Classical { .. }) => {
340
                    return Err(QASM2ParseError::new_err(message_generic(
2✔
341
                        None,
2✔
342
                        &format!("duplicate custom classical function '{}'", &classical.name,),
2✔
343
                    )));
2✔
344
                }
345
                _ => (),
520✔
346
            }
347
        }
348
        Ok(state)
1,268✔
349
    }
1,292✔
350

351
    /// Get the next token available in the stack of token streams, popping and removing any
352
    /// complete streams, except the base case.  Will only return `None` once all streams are
353
    /// exhausted.
354
    fn next_token(&mut self) -> PyResult<Option<Token>> {
49,922✔
355
        let mut pointer = self.tokens.len() - 1;
49,922✔
356
        while pointer > 0 {
49,924✔
357
            let out = self.tokens[pointer].next(&mut self.context)?;
140✔
358
            if out.is_some() {
140✔
359
                return Ok(out);
138✔
360
            }
2✔
361
            self.tokens.pop();
2✔
362
            pointer -= 1;
2✔
363
        }
364
        self.tokens[0].next(&mut self.context)
49,784✔
365
    }
49,922✔
366

367
    /// Peek the next token in the stack of token streams.  This does not remove any complete
368
    /// streams yet.  Will only return `None` once all streams are exhausted.
369
    fn peek_token(&mut self) -> PyResult<Option<&Token>> {
31,382✔
370
        let mut pointer = self.tokens.len() - 1;
31,382✔
371
        while pointer > 0 && self.tokens[pointer].peek(&mut self.context)?.is_none() {
31,400✔
372
            pointer -= 1;
18✔
373
        }
18✔
374
        self.tokens[pointer].peek(&mut self.context)
31,382✔
375
    }
31,382✔
376

377
    /// Get the filename associated with the currently active token stream.
378
    fn current_filename(&self) -> &std::ffi::OsStr {
608✔
379
        &self.tokens[self.tokens.len() - 1].filename
608✔
380
    }
608✔
381

382
    /// Take a token from the stream that is known to be present and correct, generally because it
383
    /// has already been peeked.  Panics if the token type is not correct.
384
    fn expect_known(&mut self, expected: TokenType) -> Token {
7,562✔
385
        let out = self.next_token().unwrap().unwrap();
7,562✔
386
        if out.ttype != expected {
7,562✔
387
            panic!(
×
388
                "expected '{}' but got '{}'",
×
389
                expected.describe(),
×
390
                out.ttype.describe()
×
391
            )
×
392
        }
7,562✔
393
        out
7,562✔
394
    }
7,562✔
395

396
    /// Take the next token from the stream, expecting that it is of a particular type because it
397
    /// is required to be in order for the input program to be valid OpenQASM 2.  This returns the
398
    /// token if successful, and a suitable error message if the token type is incorrect, or the
399
    /// end of the file is reached.
400
    fn expect(&mut self, expected: TokenType, required: &str, cause: &Token) -> PyResult<Token> {
28,424✔
401
        let token = match self.next_token()? {
28,424✔
402
            None => {
403
                return Err(QASM2ParseError::new_err(message_bad_eof(
114✔
404
                    Some(&Position::new(
114✔
405
                        self.current_filename(),
114✔
406
                        cause.line,
114✔
407
                        cause.col,
114✔
408
                    )),
114✔
409
                    required,
114✔
410
                )))
114✔
411
            }
412
            Some(token) => token,
28,292✔
413
        };
28,292✔
414
        if token.ttype == expected {
28,292✔
415
            Ok(token)
28,120✔
416
        } else {
417
            Err(QASM2ParseError::new_err(message_incorrect_requirement(
172✔
418
                required,
172✔
419
                &token,
172✔
420
                self.current_filename(),
172✔
421
            )))
172✔
422
        }
423
    }
28,424✔
424

425
    /// Take the next token from the stream, if it is of the correct type.  Returns `None` and
426
    /// leaves the next token in the underlying iterator if it does not match.
427
    fn accept(&mut self, expected: TokenType) -> PyResult<Option<Token>> {
20,372✔
428
        let peeked = self.peek_token()?;
20,372✔
429
        if peeked.is_some() && peeked.unwrap().ttype == expected {
20,372✔
430
            self.next_token()
13,904✔
431
        } else {
432
            Ok(None)
6,468✔
433
        }
434
    }
20,372✔
435

436
    /// True if the next token in the stream matches the given type, and false if it doesn't.
437
    fn next_is(&mut self, expected: TokenType) -> PyResult<bool> {
1,910✔
438
        let peeked = self.peek_token()?;
1,910✔
439
        Ok(peeked.is_some() && peeked.unwrap().ttype == expected)
1,906✔
440
    }
1,910✔
441

442
    /// If in `strict` mode, and we have a trailing comma, emit a suitable error message.
443
    fn check_trailing_comma(&self, comma: Option<&Token>) -> PyResult<()> {
3,968✔
444
        match (self.strict, comma) {
3,968✔
445
            (true, Some(token)) => Err(QASM2ParseError::new_err(message_generic(
14✔
446
                Some(&Position::new(
14✔
447
                    self.current_filename(),
14✔
448
                    token.line,
14✔
449
                    token.col,
14✔
450
                )),
14✔
451
                "[strict] trailing commas in parameter and qubit lists are forbidden",
14✔
452
            ))),
14✔
453
            _ => Ok(()),
3,954✔
454
        }
455
    }
3,968✔
456

457
    /// Take a complete quantum argument from the token stream, if the next token is an identifier.
458
    /// This includes resolving any following subscript operation.  Returns an error variant if the
459
    /// next token _is_ an identifier, but the symbol represents something other than a quantum
460
    /// register, or isn't defined.  This can also be an error if the subscript is opened, but
461
    /// cannot be completely resolved due to a typing error or other invalid parse.  `Ok(None)` is
462
    /// returned if the next token in the stream does not match a possible quantum argument.
463
    fn accept_qarg(&mut self) -> PyResult<Option<Operand<QubitId>>> {
4,356✔
464
        let (name, name_token) = match self.accept(TokenType::Id)? {
4,356✔
465
            None => return Ok(None),
34✔
466
            Some(token) => (token.id(&self.context), token),
4,322✔
467
        };
468
        let (register_size, register_start) = match self.symbols.get(&name) {
4,322✔
469
            Some(GlobalSymbol::Qreg { size, start }) => (*size, *start),
4,300✔
470
            Some(symbol) => {
18✔
471
                return Err(QASM2ParseError::new_err(message_generic(
18✔
472
                    Some(&Position::new(
18✔
473
                        self.current_filename(),
18✔
474
                        name_token.line,
18✔
475
                        name_token.col,
18✔
476
                    )),
18✔
477
                    &format!(
18✔
478
                        "'{}' is {}, not a quantum register",
18✔
479
                        name,
18✔
480
                        symbol.describe()
18✔
481
                    ),
18✔
482
                )))
18✔
483
            }
484
            None => {
485
                return Err(QASM2ParseError::new_err(message_generic(
4✔
486
                    Some(&Position::new(
4✔
487
                        self.current_filename(),
4✔
488
                        name_token.line,
4✔
489
                        name_token.col,
4✔
490
                    )),
4✔
491
                    &format!("'{}' is not defined in this scope", name),
4✔
492
                )))
4✔
493
            }
494
        };
495
        self.complete_operand(&name, register_size, register_start)
4,300✔
496
            .map(Some)
4,300✔
497
    }
4,356✔
498

499
    /// Take a complete quantum argument from the stream, if it matches.  This is for use within
500
    /// gates, and so the only valid type of quantum argument is a single qubit.
501
    fn accept_qarg_gate(&mut self) -> PyResult<Option<Operand<QubitId>>> {
406✔
502
        let (name, name_token) = match self.accept(TokenType::Id)? {
406✔
503
            None => return Ok(None),
×
504
            Some(token) => (token.id(&self.context), token),
406✔
505
        };
406✔
506
        match self.gate_symbols.get(&name) {
406✔
507
            Some(GateSymbol::Qubit { index }) => Ok(Some(Operand::Single(*index))),
394✔
508
            Some(GateSymbol::Parameter { .. }) => Err(QASM2ParseError::new_err(message_generic(
2✔
509
                Some(&Position::new(
2✔
510
                    self.current_filename(),
2✔
511
                    name_token.line,
2✔
512
                    name_token.col,
2✔
513
                )),
2✔
514
                &format!("'{}' is a parameter, not a qubit", name),
2✔
515
            ))),
2✔
516
            None => {
517
                if let Some(symbol) = self.symbols.get(&name) {
10✔
518
                    Err(QASM2ParseError::new_err(message_generic(
8✔
519
                        Some(&Position::new(
8✔
520
                            self.current_filename(),
8✔
521
                            name_token.line,
8✔
522
                            name_token.col,
8✔
523
                        )),
8✔
524
                        &format!("'{}' is {}, not a qubit", name, symbol.describe()),
8✔
525
                    )))
8✔
526
                } else {
527
                    Err(QASM2ParseError::new_err(message_generic(
2✔
528
                        Some(&Position::new(
2✔
529
                            self.current_filename(),
2✔
530
                            name_token.line,
2✔
531
                            name_token.col,
2✔
532
                        )),
2✔
533
                        &format!("'{}' is not defined in this scope", name),
2✔
534
                    )))
2✔
535
                }
536
            }
537
        }
538
    }
406✔
539

540
    /// Take a complete quantum argument from the token stream, returning an error message if one
541
    /// is not present.
542
    fn require_qarg(&mut self, instruction: &Token) -> PyResult<Operand<QubitId>> {
492✔
543
        match self.peek_token()?.map(|tok| tok.ttype) {
492✔
544
            Some(TokenType::Id) => self.accept_qarg().map(Option::unwrap),
488✔
545
            Some(_) => {
546
                let token = self.next_token()?;
×
547
                Err(QASM2ParseError::new_err(message_incorrect_requirement(
×
548
                    "a quantum argument",
×
549
                    &token.unwrap(),
×
550
                    self.current_filename(),
×
551
                )))
×
552
            }
553
            None => Err(QASM2ParseError::new_err(message_bad_eof(
4✔
554
                Some(&Position::new(
4✔
555
                    self.current_filename(),
4✔
556
                    instruction.line,
4✔
557
                    instruction.col,
4✔
558
                )),
4✔
559
                "a quantum argument",
4✔
560
            ))),
4✔
561
        }
562
    }
492✔
563

564
    /// Take a complete classical argument from the token stream, if the next token is an
565
    /// identifier.  This includes resolving any following subscript operation.  Returns an error
566
    /// variant if the next token _is_ an identifier, but the symbol represents something other
567
    /// than a classical register, or isn't defined.  This can also be an error if the subscript is
568
    /// opened, but cannot be completely resolved due to a typing error or other invalid parse.
569
    /// `Ok(None)` is returned if the next token in the stream does not match a possible classical
570
    /// argument.
571
    fn accept_carg(&mut self) -> PyResult<Option<Operand<ClbitId>>> {
416✔
572
        let (name, name_token) = match self.accept(TokenType::Id)? {
416✔
573
            None => return Ok(None),
×
574
            Some(token) => (token.id(&self.context), token),
416✔
575
        };
576
        let (register_size, register_start) = match self.symbols.get(&name) {
416✔
577
            Some(GlobalSymbol::Creg { size, start, .. }) => (*size, *start),
408✔
578
            Some(symbol) => {
6✔
579
                return Err(QASM2ParseError::new_err(message_generic(
6✔
580
                    Some(&Position::new(
6✔
581
                        self.current_filename(),
6✔
582
                        name_token.line,
6✔
583
                        name_token.col,
6✔
584
                    )),
6✔
585
                    &format!(
6✔
586
                        "'{}' is {}, not a classical register",
6✔
587
                        name,
6✔
588
                        symbol.describe()
6✔
589
                    ),
6✔
590
                )))
6✔
591
            }
592
            None => {
593
                return Err(QASM2ParseError::new_err(message_generic(
2✔
594
                    Some(&Position::new(
2✔
595
                        self.current_filename(),
2✔
596
                        name_token.line,
2✔
597
                        name_token.col,
2✔
598
                    )),
2✔
599
                    &format!("'{}' is not defined in this scope", name),
2✔
600
                )))
2✔
601
            }
602
        };
603
        self.complete_operand(&name, register_size, register_start)
408✔
604
            .map(Some)
408✔
605
    }
416✔
606

607
    /// Take a complete classical argument from the token stream, returning an error message if one
608
    /// is not present.
609
    fn require_carg(&mut self, instruction: &Token) -> PyResult<Operand<ClbitId>> {
418✔
610
        match self.peek_token()?.map(|tok| tok.ttype) {
418✔
611
            Some(TokenType::Id) => self.accept_carg().map(Option::unwrap),
416✔
612
            Some(_) => {
613
                let token = self.next_token()?;
×
614
                Err(QASM2ParseError::new_err(message_incorrect_requirement(
×
615
                    "a classical argument",
×
616
                    &token.unwrap(),
×
617
                    self.current_filename(),
×
618
                )))
×
619
            }
620
            None => Err(QASM2ParseError::new_err(message_bad_eof(
2✔
621
                Some(&Position::new(
2✔
622
                    self.current_filename(),
2✔
623
                    instruction.line,
2✔
624
                    instruction.col,
2✔
625
                )),
2✔
626
                "a classical argument",
2✔
627
            ))),
2✔
628
        }
629
    }
418✔
630

631
    /// Evaluate a possible subscript on a register into a final [Operand], consuming the tokens
632
    /// (if present) from the stream.  Can return error variants if the subscript cannot be
633
    /// completed or if there is a parse error while reading the subscript.
634
    fn complete_operand<T>(
4,708✔
635
        &mut self,
4,708✔
636
        name: &str,
4,708✔
637
        register_size: usize,
4,708✔
638
        register_start: T,
4,708✔
639
    ) -> PyResult<Operand<T>>
4,708✔
640
    where
4,708✔
641
        T: std::ops::Add<usize, Output = T>,
4,708✔
642
    {
4,708✔
643
        let lbracket_token = match self.accept(TokenType::LBracket)? {
4,708✔
644
            Some(token) => token,
4,020✔
645
            None => return Ok(Operand::Range(register_size, register_start)),
688✔
646
        };
647
        let index_token = self.expect(TokenType::Integer, "an integer index", &lbracket_token)?;
4,020✔
648
        let index = index_token.int(&self.context);
3,998✔
649
        self.expect(TokenType::RBracket, "a closing bracket", &lbracket_token)?;
3,998✔
650
        if index < register_size {
3,976✔
651
            Ok(Operand::Single(register_start + index))
3,970✔
652
        } else {
653
            Err(QASM2ParseError::new_err(message_generic(
6✔
654
                Some(&Position::new(
6✔
655
                    self.current_filename(),
6✔
656
                    index_token.line,
6✔
657
                    index_token.col,
6✔
658
                )),
6✔
659
                &format!(
6✔
660
                    "index {} is out-of-range for register '{}' of size {}",
6✔
661
                    index, name, register_size
6✔
662
                ),
6✔
663
            )))
6✔
664
        }
665
    }
4,708✔
666

667
    /// Parse an `OPENQASM <version>;` statement completely.  This function does not need to take
668
    /// the bytecode stream because the version information has no actionable effects for Qiskit
669
    /// to care about.  We simply error if the version supplied by the file is not the version of
670
    /// OpenQASM that we are able to support.  This assumes that the `OPENQASM` token is still in
671
    /// the stream.
672
    fn parse_version(&mut self) -> PyResult<usize> {
624✔
673
        let openqasm_token = self.expect_known(TokenType::OpenQASM);
624✔
674
        let version_token = self.expect(TokenType::Version, "version number", &openqasm_token)?;
624✔
675
        match version_token.version(&self.context) {
608✔
676
            Version {
677
                major: 2,
678
                minor: Some(0) | None,
679
            } => Ok(()),
604✔
680
            _ => Err(QASM2ParseError::new_err(message_generic(
4✔
681
                Some(&Position::new(
4✔
682
                    self.current_filename(),
4✔
683
                    version_token.line,
4✔
684
                    version_token.col,
4✔
685
                )),
4✔
686
                &format!(
4✔
687
                    "can only handle OpenQASM 2.0, but given {}",
4✔
688
                    version_token.text(&self.context),
4✔
689
                ),
4✔
690
            ))),
4✔
691
        }?;
4✔
692
        self.expect(TokenType::Semicolon, ";", &openqasm_token)?;
604✔
693
        Ok(0)
600✔
694
    }
624✔
695

696
    /// Parse a complete gate definition (including the body of the definition).  This assumes that
697
    /// the `gate` token is still in the scheme.  This function will likely result in many
698
    /// instructions being pushed onto the bytecode stream; one for the start and end of the gate
699
    /// definition, and then one instruction each for the gate applications in the body.
700
    fn parse_gate_definition(&mut self, bc: &mut Vec<Option<InternalBytecode>>) -> PyResult<usize> {
288✔
701
        let gate_token = self.expect_known(TokenType::Gate);
288✔
702
        let name_token = self.expect(TokenType::Id, "an identifier", &gate_token)?;
288✔
703
        let name = name_token.id(&self.context);
284✔
704
        // Parse the gate parameters (if any) into the symbol take.
284✔
705
        let mut num_params = 0usize;
284✔
706
        if let Some(lparen_token) = self.accept(TokenType::LParen)? {
284✔
707
            let mut comma = None;
156✔
708
            while let Some(param_token) = self.accept(TokenType::Id)? {
278✔
709
                let param_name = param_token.id(&self.context);
264✔
710
                if let Some(symbol) = self.gate_symbols.insert(
264✔
711
                    param_name.to_owned(),
264✔
712
                    GateSymbol::Parameter {
264✔
713
                        index: ParamId::new(num_params),
264✔
714
                    },
264✔
715
                ) {
264✔
716
                    return Err(QASM2ParseError::new_err(message_generic(
2✔
717
                        Some(&Position::new(
2✔
718
                            self.current_filename(),
2✔
719
                            param_token.line,
2✔
720
                            param_token.col,
2✔
721
                        )),
2✔
722
                        &format!(
2✔
723
                            "'{}' is already defined as {}",
2✔
724
                            param_name,
2✔
725
                            symbol.describe()
2✔
726
                        ),
2✔
727
                    )));
2✔
728
                }
262✔
729
                num_params += 1;
262✔
730
                comma = self.accept(TokenType::Comma)?;
262✔
731
                if comma.is_none() {
262✔
732
                    break;
140✔
733
                }
122✔
734
            }
735
            self.check_trailing_comma(comma.as_ref())?;
154✔
736
            self.expect(TokenType::RParen, "a closing parenthesis", &lparen_token)?;
152✔
737
        }
128✔
738
        // Parse the quantum parameters into the symbol table.
739
        let mut num_qubits = 0usize;
266✔
740
        let mut comma = None;
266✔
741
        while let Some(qubit_token) = self.accept(TokenType::Id)? {
394✔
742
            let qubit_name = qubit_token.id(&self.context).to_owned();
376✔
743
            if let Some(symbol) = self.gate_symbols.insert(
376✔
744
                qubit_name.to_owned(),
376✔
745
                GateSymbol::Qubit {
376✔
746
                    index: QubitId::new(num_qubits),
376✔
747
                },
376✔
748
            ) {
376✔
749
                return Err(QASM2ParseError::new_err(message_generic(
4✔
750
                    Some(&Position::new(
4✔
751
                        self.current_filename(),
4✔
752
                        qubit_token.line,
4✔
753
                        qubit_token.col,
4✔
754
                    )),
4✔
755
                    &format!(
4✔
756
                        "'{}' is already defined as {}",
4✔
757
                        qubit_name,
4✔
758
                        symbol.describe()
4✔
759
                    ),
4✔
760
                )));
4✔
761
            }
372✔
762
            num_qubits += 1;
372✔
763
            comma = self.accept(TokenType::Comma)?;
372✔
764
            if comma.is_none() {
372✔
765
                break;
244✔
766
            }
128✔
767
        }
768
        self.check_trailing_comma(comma.as_ref())?;
262✔
769
        if num_qubits == 0 {
260✔
770
            let eof = self.peek_token()?.is_none();
8✔
771
            let position = Position::new(self.current_filename(), gate_token.line, gate_token.col);
8✔
772
            return if eof {
8✔
773
                Err(QASM2ParseError::new_err(message_bad_eof(
4✔
774
                    Some(&position),
4✔
775
                    "a qubit identifier",
4✔
776
                )))
4✔
777
            } else {
778
                Err(QASM2ParseError::new_err(message_generic(
4✔
779
                    Some(&position),
4✔
780
                    "gates must act on at least one qubit",
4✔
781
                )))
4✔
782
            };
783
        }
252✔
784
        let lbrace_token = self.expect(TokenType::LBrace, "a gate body", &gate_token)?;
252✔
785
        bc.push(Some(InternalBytecode::DeclareGate {
238✔
786
            name: name.clone(),
238✔
787
            num_qubits,
238✔
788
        }));
238✔
789
        // The actual body of the gate.  Most of this is devolved to [Self::parse_gate_application]
238✔
790
        // to do the right thing.
238✔
791
        let mut statements = 0usize;
238✔
792
        loop {
793
            match self.peek_token()?.map(|tok| tok.ttype) {
500✔
794
                Some(TokenType::Id) => statements += self.parse_gate_application(bc, None, true)?,
286✔
795
                Some(TokenType::Barrier) => {
796
                    statements += self.parse_barrier(bc, Some(num_qubits))?
12✔
797
                }
798
                Some(TokenType::RBrace) => {
799
                    self.expect_known(TokenType::RBrace);
192✔
800
                    break;
192✔
801
                }
802
                Some(_) => {
803
                    let token = self.next_token()?.unwrap();
8✔
804
                    return Err(QASM2ParseError::new_err(message_generic(
8✔
805
                        Some(&Position::new(
8✔
806
                            self.current_filename(),
8✔
807
                            token.line,
8✔
808
                            token.col,
8✔
809
                        )),
8✔
810
                        &format!(
8✔
811
                            "only gate applications are valid within a 'gate' body, but saw {}",
8✔
812
                            token.text(&self.context)
8✔
813
                        ),
8✔
814
                    )));
8✔
815
                }
816
                None => {
817
                    return Err(QASM2ParseError::new_err(message_bad_eof(
2✔
818
                        Some(&Position::new(
2✔
819
                            self.current_filename(),
2✔
820
                            lbrace_token.line,
2✔
821
                            lbrace_token.col,
2✔
822
                        )),
2✔
823
                        "a closing brace '}' of the gate body",
2✔
824
                    )))
2✔
825
                }
826
            }
827
        }
828
        bc.push(Some(InternalBytecode::EndDeclareGate {}));
192✔
829
        self.gate_symbols.clear();
192✔
830
        self.define_gate(Some(&gate_token), name, num_params, num_qubits)?;
192✔
831
        Ok(statements + 2)
168✔
832
    }
288✔
833

834
    /// Parse an `opaque` statement.  This assumes that the `opaque` token is still in the token
835
    /// stream we are reading from.
836
    fn parse_opaque_definition(
100✔
837
        &mut self,
100✔
838
        bc: &mut Vec<Option<InternalBytecode>>,
100✔
839
    ) -> PyResult<usize> {
100✔
840
        let opaque_token = self.expect_known(TokenType::Opaque);
100✔
841
        let name = self
100✔
842
            .expect(TokenType::Id, "an identifier", &opaque_token)?
100✔
843
            .text(&self.context)
94✔
844
            .to_owned();
94✔
845
        let mut num_params = 0usize;
94✔
846
        if let Some(lparen_token) = self.accept(TokenType::LParen)? {
94✔
847
            let mut comma = None;
78✔
848
            while self.accept(TokenType::Id)?.is_some() {
128✔
849
                num_params += 1;
116✔
850
                comma = self.accept(TokenType::Comma)?;
116✔
851
                if comma.is_none() {
116✔
852
                    break;
66✔
853
                }
50✔
854
            }
855
            self.check_trailing_comma(comma.as_ref())?;
78✔
856
            self.expect(TokenType::RParen, "closing parenthesis", &lparen_token)?;
76✔
857
        }
16✔
858
        let mut num_qubits = 0usize;
74✔
859
        let mut comma = None;
74✔
860
        while self.accept(TokenType::Id)?.is_some() {
102✔
861
            num_qubits += 1;
76✔
862
            comma = self.accept(TokenType::Comma)?;
76✔
863
            if comma.is_none() {
76✔
864
                break;
48✔
865
            }
28✔
866
        }
867
        self.check_trailing_comma(comma.as_ref())?;
74✔
868
        self.expect(TokenType::Semicolon, ";", &opaque_token)?;
72✔
869
        if num_qubits == 0 {
48✔
870
            return Err(QASM2ParseError::new_err(message_generic(
4✔
871
                Some(&Position::new(
4✔
872
                    self.current_filename(),
4✔
873
                    opaque_token.line,
4✔
874
                    opaque_token.col,
4✔
875
                )),
4✔
876
                "gates must act on at least one qubit",
4✔
877
            )));
4✔
878
        }
44✔
879
        bc.push(Some(InternalBytecode::DeclareOpaque {
44✔
880
            name: name.clone(),
44✔
881
            num_qubits,
44✔
882
        }));
44✔
883
        self.define_gate(Some(&opaque_token), name, num_params, num_qubits)?;
44✔
884
        Ok(1)
36✔
885
    }
100✔
886

887
    /// Parse a gate application into the bytecode stream.  This resolves any broadcast over
888
    /// registers into a series of bytecode instructions, rather than leaving Qiskit to do it,
889
    /// which would involve much slower Python execution.  This assumes that the identifier token
890
    /// is still in the token stream.
891
    fn parse_gate_application(
2,608✔
892
        &mut self,
2,608✔
893
        bc: &mut Vec<Option<InternalBytecode>>,
2,608✔
894
        condition: Option<Condition>,
2,608✔
895
        in_gate: bool,
2,608✔
896
    ) -> PyResult<usize> {
2,608✔
897
        let name_token = self.expect_known(TokenType::Id);
2,608✔
898
        let name = name_token.id(&self.context);
2,608✔
899
        let (index, num_params, num_qubits) = match self.symbols.get(&name) {
2,608✔
900
            Some(GlobalSymbol::Gate {
901
                num_params,
2,594✔
902
                num_qubits,
2,594✔
903
                index,
2,594✔
904
            }) => Ok((*index, *num_params, *num_qubits)),
2,594✔
905
            Some(symbol) => Err(QASM2ParseError::new_err(message_generic(
6✔
906
                Some(&Position::new(
6✔
907
                    self.current_filename(),
6✔
908
                    name_token.line,
6✔
909
                    name_token.col,
6✔
910
                )),
6✔
911
                &format!("'{}' is {}, not a gate", name, symbol.describe()),
6✔
912
            ))),
6✔
913
            None => {
914
                let pos = Position::new(self.current_filename(), name_token.line, name_token.col);
8✔
915
                let message = if self.overridable_gates.contains_key(&name) {
8✔
916
                    format!(
2✔
917
                        "cannot use non-builtin custom instruction '{}' before definition",
2✔
918
                        name,
2✔
919
                    )
2✔
920
                } else {
921
                    format!("'{}' is not defined in this scope", name)
6✔
922
                };
923
                Err(QASM2ParseError::new_err(message_generic(
8✔
924
                    Some(&pos),
8✔
925
                    &message,
8✔
926
                )))
8✔
927
            }
928
        }?;
14✔
929
        let parameters = self.expect_gate_parameters(&name_token, num_params, in_gate)?;
2,594✔
930
        let mut qargs = Vec::<Operand<QubitId>>::with_capacity(num_qubits);
2,482✔
931
        let mut comma = None;
2,482✔
932
        if in_gate {
2,482✔
933
            while let Some(qarg) = self.accept_qarg_gate()? {
388✔
934
                qargs.push(qarg);
376✔
935
                comma = self.accept(TokenType::Comma)?;
376✔
936
                if comma.is_none() {
376✔
937
                    break;
252✔
938
                }
124✔
939
            }
940
        } else {
941
            while let Some(qarg) = self.accept_qarg()? {
3,580✔
942
                qargs.push(qarg);
3,532✔
943
                comma = self.accept(TokenType::Comma)?;
3,532✔
944
                if comma.is_none() {
3,532✔
945
                    break;
2,170✔
946
                }
1,362✔
947
            }
948
        }
949
        self.check_trailing_comma(comma.as_ref())?;
2,448✔
950
        if qargs.len() != num_qubits {
2,446✔
951
            return match self.peek_token()?.map(|tok| tok.ttype) {
42✔
952
                Some(TokenType::Semicolon) => Err(QASM2ParseError::new_err(message_generic(
953
                    Some(&Position::new(
16✔
954
                        self.current_filename(),
16✔
955
                        name_token.line,
16✔
956
                        name_token.col,
16✔
957
                    )),
16✔
958
                    &format!(
16✔
959
                        "'{}' takes {} quantum argument{}, but got {}",
16✔
960
                        name,
16✔
961
                        num_qubits,
16✔
962
                        if num_qubits == 1 { "" } else { "s" },
16✔
963
                        qargs.len()
16✔
964
                    ),
965
                ))),
966
                Some(_) => Err(QASM2ParseError::new_err(message_incorrect_requirement(
16✔
967
                    "the end of the argument list",
16✔
968
                    &name_token,
16✔
969
                    self.current_filename(),
16✔
970
                ))),
16✔
971
                None => Err(QASM2ParseError::new_err(message_bad_eof(
10✔
972
                    Some(&Position::new(
10✔
973
                        self.current_filename(),
10✔
974
                        name_token.line,
10✔
975
                        name_token.col,
10✔
976
                    )),
10✔
977
                    "the end of the argument list",
10✔
978
                ))),
10✔
979
            };
980
        }
2,404✔
981
        self.expect(TokenType::Semicolon, "';'", &name_token)?;
2,404✔
982
        self.emit_gate_application(bc, &name_token, index, parameters, &qargs, condition)
2,398✔
983
    }
2,608✔
984

985
    /// Parse the parameters (if any) from a gate application.
986
    fn expect_gate_parameters(
2,594✔
987
        &mut self,
2,594✔
988
        name_token: &Token,
2,594✔
989
        num_params: usize,
2,594✔
990
        in_gate: bool,
2,594✔
991
    ) -> PyResult<GateParameters> {
2,594✔
992
        let lparen_token = match self.accept(TokenType::LParen)? {
2,594✔
993
            Some(lparen_token) => lparen_token,
890✔
994
            None => {
995
                return Ok(if in_gate {
1,704✔
996
                    GateParameters::Expression(vec![])
164✔
997
                } else {
998
                    GateParameters::Constant(vec![])
1,540✔
999
                });
1000
            }
1001
        };
1002
        let mut seen_params = 0usize;
890✔
1003
        let mut comma = None;
890✔
1004
        // This code duplication is to avoid duplication of allocation when parsing the far more
1005
        // common case of expecting constant parameters for a gate application in the body of the
1006
        // OQ2 file.
1007
        let parameters = if in_gate {
890✔
1008
            let mut parameters = Vec::<Expr>::with_capacity(num_params);
120✔
1009
            while !self.next_is(TokenType::RParen)? {
242✔
1010
                let mut expr_parser = ExprParser {
242✔
1011
                    tokens: &mut self.tokens,
242✔
1012
                    context: &mut self.context,
242✔
1013
                    gate_symbols: &self.gate_symbols,
242✔
1014
                    global_symbols: &self.symbols,
242✔
1015
                    strict: self.strict,
242✔
1016
                };
242✔
1017
                parameters.push(expr_parser.parse_expression(&lparen_token)?);
242✔
1018
                seen_params += 1;
222✔
1019
                comma = self.accept(TokenType::Comma)?;
222✔
1020
                if comma.is_none() {
222✔
1021
                    break;
100✔
1022
                }
122✔
1023
            }
1024
            self.expect(TokenType::RParen, "')'", &lparen_token)?;
100✔
1025
            GateParameters::Expression(parameters)
100✔
1026
        } else {
1027
            let mut parameters = Vec::<f64>::with_capacity(num_params);
770✔
1028
            while !self.next_is(TokenType::RParen)? {
1,480✔
1029
                let mut expr_parser = ExprParser {
1,440✔
1030
                    tokens: &mut self.tokens,
1,440✔
1031
                    context: &mut self.context,
1,440✔
1032
                    gate_symbols: &self.gate_symbols,
1,440✔
1033
                    global_symbols: &self.symbols,
1,440✔
1034
                    strict: self.strict,
1,440✔
1035
                };
1,440✔
1036
                match expr_parser.parse_expression(&lparen_token)? {
1,440✔
1037
                    Expr::Constant(value) => parameters.push(value),
1,366✔
1038
                    _ => {
1039
                        return Err(QASM2ParseError::new_err(message_generic(
×
1040
                            Some(&Position::new(
×
1041
                                self.current_filename(),
×
1042
                                lparen_token.line,
×
1043
                                lparen_token.col,
×
1044
                            )),
×
1045
                            "non-constant expression in program body",
×
1046
                        )))
×
1047
                    }
1048
                }
1049
                seen_params += 1;
1,366✔
1050
                comma = self.accept(TokenType::Comma)?;
1,366✔
1051
                if comma.is_none() {
1,366✔
1052
                    break;
656✔
1053
                }
710✔
1054
            }
1055
            self.expect(TokenType::RParen, "')'", &lparen_token)?;
692✔
1056
            GateParameters::Constant(parameters)
692✔
1057
        };
1058
        self.check_trailing_comma(comma.as_ref())?;
792✔
1059
        if seen_params != num_params {
790✔
1060
            return Err(QASM2ParseError::new_err(message_generic(
1061
                Some(&Position::new(
12✔
1062
                    self.current_filename(),
12✔
1063
                    name_token.line,
12✔
1064
                    name_token.col,
12✔
1065
                )),
12✔
1066
                &format!(
12✔
1067
                    "'{}' takes {} parameter{}, but got {}",
12✔
1068
                    &name_token.text(&self.context),
12✔
1069
                    num_params,
12✔
1070
                    if num_params == 1 { "" } else { "s" },
12✔
1071
                    seen_params
1072
                ),
1073
            )));
1074
        }
778✔
1075
        Ok(parameters)
778✔
1076
    }
2,594✔
1077

1078
    /// Emit the bytecode for the application of a gate.  This involves resolving any broadcasts
1079
    /// in the operands of the gate (i.e. if one or more of them is a register).
1080
    fn emit_gate_application(
2,398✔
1081
        &self,
2,398✔
1082
        bc: &mut Vec<Option<InternalBytecode>>,
2,398✔
1083
        instruction: &Token,
2,398✔
1084
        gate_id: GateId,
2,398✔
1085
        parameters: GateParameters,
2,398✔
1086
        qargs: &[Operand<QubitId>],
2,398✔
1087
        condition: Option<Condition>,
2,398✔
1088
    ) -> PyResult<usize> {
2,398✔
1089
        // Fast path for most common gate patterns that don't need broadcasting.
1090
        if let Some(qubits) = match qargs {
1,928✔
1091
            [Operand::Single(index)] => Some(vec![*index]),
1,240✔
1092
            [Operand::Single(left), Operand::Single(right)] => {
692✔
1093
                if *left == *right {
692✔
1094
                    return Err(QASM2ParseError::new_err(message_generic(
4✔
1095
                        Some(&Position::new(
4✔
1096
                            self.current_filename(),
4✔
1097
                            instruction.line,
4✔
1098
                            instruction.col,
4✔
1099
                        )),
4✔
1100
                        "duplicate qubits in gate application",
4✔
1101
                    )));
4✔
1102
                }
688✔
1103
                Some(vec![*left, *right])
688✔
1104
            }
1105
            [] => Some(vec![]),
324✔
1106
            _ => None,
466✔
1107
        } {
1108
            return match parameters {
1,928✔
1109
                GateParameters::Constant(parameters) => {
1,688✔
1110
                    self.emit_single_global_gate(bc, gate_id, parameters, qubits, condition)
1,688✔
1111
                }
1112
                GateParameters::Expression(parameters) => {
240✔
1113
                    self.emit_single_gate_gate(bc, gate_id, parameters, qubits)
240✔
1114
                }
1115
            };
1116
        };
466✔
1117
        // If we're here we either have to broadcast or it's a 3+q gate - either way, we're not as
466✔
1118
        // worried about performance.
466✔
1119
        let mut qubits = HashSet::<QubitId>::with_capacity(qargs.len());
466✔
1120
        let mut broadcast_length = 0usize;
466✔
1121
        for qarg in qargs {
1,616✔
1122
            match qarg {
1,206✔
1123
                Operand::Single(index) => {
874✔
1124
                    if !qubits.insert(*index) {
874✔
1125
                        return Err(QASM2ParseError::new_err(message_generic(
12✔
1126
                            Some(&Position::new(
12✔
1127
                                self.current_filename(),
12✔
1128
                                instruction.line,
12✔
1129
                                instruction.col,
12✔
1130
                            )),
12✔
1131
                            "duplicate qubits in gate application",
12✔
1132
                        )));
12✔
1133
                    }
862✔
1134
                }
1135
                Operand::Range(size, start) => {
332✔
1136
                    if broadcast_length != 0 && broadcast_length != *size {
332✔
1137
                        return Err(QASM2ParseError::new_err(message_generic(
36✔
1138
                            Some(&Position::new(
36✔
1139
                                self.current_filename(),
36✔
1140
                                instruction.line,
36✔
1141
                                instruction.col,
36✔
1142
                            )),
36✔
1143
                            "cannot resolve broadcast in gate application",
36✔
1144
                        )));
36✔
1145
                    }
296✔
1146
                    for offset in 0..*size {
636✔
1147
                        if !qubits.insert(*start + offset) {
636✔
1148
                            return Err(QASM2ParseError::new_err(message_generic(
8✔
1149
                                Some(&Position::new(
8✔
1150
                                    self.current_filename(),
8✔
1151
                                    instruction.line,
8✔
1152
                                    instruction.col,
8✔
1153
                                )),
8✔
1154
                                "duplicate qubits in gate application",
8✔
1155
                            )));
8✔
1156
                        }
628✔
1157
                    }
1158
                    broadcast_length = *size;
288✔
1159
                }
1160
            }
1161
        }
1162
        if broadcast_length == 0 {
410✔
1163
            let qubits = qargs
294✔
1164
                .iter()
294✔
1165
                .filter_map(|qarg| {
886✔
1166
                    if let Operand::Single(index) = qarg {
886✔
1167
                        Some(*index)
818✔
1168
                    } else {
1169
                        None
68✔
1170
                    }
1171
                })
886✔
1172
                .collect::<Vec<_>>();
294✔
1173
            if qubits.len() < qargs.len() {
294✔
1174
                // We're broadcasting against at least one empty register.
1175
                return Ok(0);
44✔
1176
            }
250✔
1177
            return match parameters {
250✔
1178
                GateParameters::Constant(parameters) => {
240✔
1179
                    self.emit_single_global_gate(bc, gate_id, parameters, qubits, condition)
240✔
1180
                }
1181
                GateParameters::Expression(parameters) => {
10✔
1182
                    self.emit_single_gate_gate(bc, gate_id, parameters, qubits)
10✔
1183
                }
1184
            };
1185
        }
116✔
1186
        for i in 0..broadcast_length {
342✔
1187
            let qubits = qargs
342✔
1188
                .iter()
342✔
1189
                .map(|qarg| match qarg {
528✔
1190
                    Operand::Single(index) => *index,
48✔
1191
                    Operand::Range(_, start) => *start + i,
480✔
1192
                })
528✔
1193
                .collect::<Vec<_>>();
342✔
1194
            match parameters {
342✔
1195
                GateParameters::Constant(ref parameters) => {
342✔
1196
                    self.emit_single_global_gate(
342✔
1197
                        bc,
342✔
1198
                        gate_id,
342✔
1199
                        parameters.clone(),
342✔
1200
                        qubits,
342✔
1201
                        condition.clone(),
342✔
1202
                    )?;
342✔
1203
                }
1204
                // Gates used in gate-body definitions can't ever broadcast, because their only
1205
                // operands are single qubits.
1206
                _ => unreachable!(),
×
1207
            }
1208
        }
1209
        Ok(broadcast_length)
116✔
1210
    }
2,398✔
1211

1212
    /// Emit the bytecode for a single gate application in the global scope.  This could
1213
    /// potentially have a classical condition.
1214
    fn emit_single_global_gate(
2,270✔
1215
        &self,
2,270✔
1216
        bc: &mut Vec<Option<InternalBytecode>>,
2,270✔
1217
        gate_id: GateId,
2,270✔
1218
        arguments: Vec<f64>,
2,270✔
1219
        qubits: Vec<QubitId>,
2,270✔
1220
        condition: Option<Condition>,
2,270✔
1221
    ) -> PyResult<usize> {
2,270✔
1222
        if let Some(condition) = condition {
2,270✔
1223
            bc.push(Some(InternalBytecode::ConditionedGate {
168✔
1224
                id: gate_id,
168✔
1225
                arguments,
168✔
1226
                qubits,
168✔
1227
                creg: condition.creg,
168✔
1228
                value: condition.value,
168✔
1229
            }));
168✔
1230
        } else {
2,102✔
1231
            bc.push(Some(InternalBytecode::Gate {
2,102✔
1232
                id: gate_id,
2,102✔
1233
                arguments,
2,102✔
1234
                qubits,
2,102✔
1235
            }));
2,102✔
1236
        }
2,102✔
1237
        Ok(1)
2,270✔
1238
    }
2,270✔
1239

1240
    /// Emit the bytecode for a single gate application in a gate-definition body.  These are not
1241
    /// allowed to be conditioned, because otherwise the containing `gate` would not be unitary.
1242
    fn emit_single_gate_gate(
250✔
1243
        &self,
250✔
1244
        bc: &mut Vec<Option<InternalBytecode>>,
250✔
1245
        gate_id: GateId,
250✔
1246
        arguments: Vec<Expr>,
250✔
1247
        qubits: Vec<QubitId>,
250✔
1248
    ) -> PyResult<usize> {
250✔
1249
        bc.push(Some(InternalBytecode::GateInBody {
250✔
1250
            id: gate_id,
250✔
1251
            arguments,
250✔
1252
            qubits,
250✔
1253
        }));
250✔
1254
        Ok(1)
250✔
1255
    }
250✔
1256

1257
    /// Parse a complete conditional statement, including the operation that follows the condition
1258
    /// (though this work is delegated to the requisite other grammar rule).  This assumes that the
1259
    /// `if` token is still on the token stream.
1260
    fn parse_conditional(&mut self, bc: &mut Vec<Option<InternalBytecode>>) -> PyResult<usize> {
280✔
1261
        let if_token = self.expect_known(TokenType::If);
280✔
1262
        let lparen_token = self.expect(TokenType::LParen, "'('", &if_token)?;
280✔
1263
        let name_token = self.expect(TokenType::Id, "classical register", &if_token)?;
276✔
1264
        self.expect(TokenType::Equals, "'=='", &if_token)?;
272✔
1265
        let value = self
264✔
1266
            .expect(TokenType::Integer, "an integer", &if_token)?
264✔
1267
            .bigint(&self.context);
258✔
1268
        self.expect(TokenType::RParen, "')'", &lparen_token)?;
258✔
1269
        let name = name_token.id(&self.context);
252✔
1270
        let creg = match self.symbols.get(&name) {
252✔
1271
            Some(GlobalSymbol::Creg { index, .. }) => Ok(*index),
246✔
1272
            Some(symbol) => Err(QASM2ParseError::new_err(message_generic(
4✔
1273
                Some(&Position::new(
4✔
1274
                    self.current_filename(),
4✔
1275
                    name_token.line,
4✔
1276
                    name_token.col,
4✔
1277
                )),
4✔
1278
                &format!(
4✔
1279
                    "'{}' is {}, not a classical register",
4✔
1280
                    name,
4✔
1281
                    symbol.describe()
4✔
1282
                ),
4✔
1283
            ))),
4✔
1284
            None => Err(QASM2ParseError::new_err(message_generic(
2✔
1285
                Some(&Position::new(
2✔
1286
                    self.current_filename(),
2✔
1287
                    name_token.line,
2✔
1288
                    name_token.col,
2✔
1289
                )),
2✔
1290
                &format!("'{}' is not defined in this scope", name),
2✔
1291
            ))),
2✔
1292
        }?;
6✔
1293
        let condition = Some(Condition { creg, value });
246✔
1294
        match self.peek_token()?.map(|tok| tok.ttype) {
246✔
1295
            Some(TokenType::Id) => self.parse_gate_application(bc, condition, false),
214✔
1296
            Some(TokenType::Measure) => self.parse_measure(bc, condition),
20✔
1297
            Some(TokenType::Reset) => self.parse_reset(bc, condition),
10✔
1298
            Some(_) => {
1299
                let token = self.next_token()?;
×
1300
                Err(QASM2ParseError::new_err(message_incorrect_requirement(
×
1301
                    "a gate application, measurement or reset",
×
1302
                    &token.unwrap(),
×
1303
                    self.current_filename(),
×
1304
                )))
×
1305
            }
1306
            None => Err(QASM2ParseError::new_err(message_bad_eof(
2✔
1307
                Some(&Position::new(
2✔
1308
                    self.current_filename(),
2✔
1309
                    if_token.line,
2✔
1310
                    if_token.col,
2✔
1311
                )),
2✔
1312
                "a gate, measurement or reset to condition",
2✔
1313
            ))),
2✔
1314
        }
1315
    }
280✔
1316

1317
    /// Parse a barrier statement.  This assumes that the `barrier` token is still in the token
1318
    /// stream.
1319
    fn parse_barrier(
188✔
1320
        &mut self,
188✔
1321
        bc: &mut Vec<Option<InternalBytecode>>,
188✔
1322
        num_gate_qubits: Option<usize>,
188✔
1323
    ) -> PyResult<usize> {
188✔
1324
        let barrier_token = self.expect_known(TokenType::Barrier);
188✔
1325
        let qubits = if !self.next_is(TokenType::Semicolon)? {
188✔
1326
            let mut qubits = Vec::new();
168✔
1327
            let mut used = HashSet::<QubitId>::new();
168✔
1328
            let mut comma = None;
168✔
1329
            while let Some(qarg) = if num_gate_qubits.is_some() {
306✔
1330
                self.accept_qarg_gate()?
18✔
1331
            } else {
1332
                self.accept_qarg()?
288✔
1333
            } {
1334
                match qarg {
290✔
1335
                    Operand::Single(index) => {
176✔
1336
                        if used.insert(index) {
176✔
1337
                            qubits.push(index)
170✔
1338
                        }
6✔
1339
                    }
1340
                    Operand::Range(size, start) => qubits.extend((0..size).filter_map(|offset| {
322✔
1341
                        let index = start + offset;
322✔
1342
                        if used.insert(index) {
322✔
1343
                            Some(index)
308✔
1344
                        } else {
1345
                            None
14✔
1346
                        }
1347
                    })),
322✔
1348
                }
1349
                comma = self.accept(TokenType::Comma)?;
290✔
1350
                if comma.is_none() {
290✔
1351
                    break;
152✔
1352
                }
138✔
1353
            }
1354
            self.check_trailing_comma(comma.as_ref())?;
160✔
1355
            qubits
158✔
1356
        } else if self.strict {
20✔
1357
            return Err(QASM2ParseError::new_err(message_generic(
2✔
1358
                Some(&Position::new(
2✔
1359
                    self.current_filename(),
2✔
1360
                    barrier_token.line,
2✔
1361
                    barrier_token.col,
2✔
1362
                )),
2✔
1363
                "[strict] barrier statements must have at least one argument",
2✔
1364
            )));
2✔
1365
        } else if let Some(num_gate_qubits) = num_gate_qubits {
18✔
1366
            (0..num_gate_qubits).map(QubitId::new).collect::<Vec<_>>()
2✔
1367
        } else {
1368
            (0..self.num_qubits).map(QubitId::new).collect::<Vec<_>>()
16✔
1369
        };
1370
        self.expect(TokenType::Semicolon, "';'", &barrier_token)?;
176✔
1371
        if qubits.is_empty() {
168✔
1372
            Ok(0)
4✔
1373
        } else {
1374
            // The qubits are empty iff the only operands are zero-sized registers.  If there's no
1375
            // quantum arguments at all, then `qubits` will contain everything.
1376
            bc.push(Some(InternalBytecode::Barrier { qubits }));
164✔
1377
            Ok(1)
164✔
1378
        }
1379
    }
188✔
1380

1381
    /// Parse a measurement operation into bytecode.  This resolves any broadcast in the
1382
    /// measurement statement into a series of bytecode instructions, so we do more of the work in
1383
    /// Rust space than in Python space.
1384
    fn parse_measure(
450✔
1385
        &mut self,
450✔
1386
        bc: &mut Vec<Option<InternalBytecode>>,
450✔
1387
        condition: Option<Condition>,
450✔
1388
    ) -> PyResult<usize> {
450✔
1389
        let measure_token = self.expect_known(TokenType::Measure);
450✔
1390
        let qarg = self.require_qarg(&measure_token)?;
450✔
1391
        self.expect(TokenType::Arrow, "'->'", &measure_token)?;
432✔
1392
        let carg = self.require_carg(&measure_token)?;
418✔
1393
        self.expect(TokenType::Semicolon, "';'", &measure_token)?;
394✔
1394
        if let Some(Condition { creg, value }) = condition {
380✔
1395
            match (qarg, carg) {
20✔
1396
                (Operand::Single(qubit), Operand::Single(clbit)) => {
4✔
1397
                    bc.push(Some(InternalBytecode::ConditionedMeasure {
4✔
1398
                        qubit,
4✔
1399
                        clbit,
4✔
1400
                        creg,
4✔
1401
                        value,
4✔
1402
                    }));
4✔
1403
                    Ok(1)
4✔
1404
                }
1405
                (Operand::Range(q_size, q_start), Operand::Range(c_size, c_start))
6✔
1406
                    if q_size == c_size =>
8✔
1407
                {
6✔
1408
                    bc.extend((0..q_size).map(|i| {
8✔
1409
                        Some(InternalBytecode::ConditionedMeasure {
8✔
1410
                            qubit: q_start + i,
8✔
1411
                            clbit: c_start + i,
8✔
1412
                            creg,
8✔
1413
                            value: value.clone(),
8✔
1414
                        })
8✔
1415
                    }));
8✔
1416
                    Ok(q_size)
6✔
1417
                }
1418
                _ => Err(QASM2ParseError::new_err(message_generic(
10✔
1419
                    Some(&Position::new(
10✔
1420
                        self.current_filename(),
10✔
1421
                        measure_token.line,
10✔
1422
                        measure_token.col,
10✔
1423
                    )),
10✔
1424
                    "cannot resolve broadcast in measurement",
10✔
1425
                ))),
10✔
1426
            }
1427
        } else {
1428
            match (qarg, carg) {
360✔
1429
                (Operand::Single(qubit), Operand::Single(clbit)) => {
266✔
1430
                    bc.push(Some(InternalBytecode::Measure { qubit, clbit }));
266✔
1431
                    Ok(1)
266✔
1432
                }
1433
                (Operand::Range(q_size, q_start), Operand::Range(c_size, c_start))
84✔
1434
                    if q_size == c_size =>
86✔
1435
                {
84✔
1436
                    bc.extend((0..q_size).map(|i| {
238✔
1437
                        Some(InternalBytecode::Measure {
238✔
1438
                            qubit: q_start + i,
238✔
1439
                            clbit: c_start + i,
238✔
1440
                        })
238✔
1441
                    }));
238✔
1442
                    Ok(q_size)
84✔
1443
                }
1444
                _ => Err(QASM2ParseError::new_err(message_generic(
10✔
1445
                    Some(&Position::new(
10✔
1446
                        self.current_filename(),
10✔
1447
                        measure_token.line,
10✔
1448
                        measure_token.col,
10✔
1449
                    )),
10✔
1450
                    "cannot resolve broadcast in measurement",
10✔
1451
                ))),
10✔
1452
            }
1453
        }
1454
    }
450✔
1455

1456
    /// Parse a single reset statement.  This resolves any broadcast in the statement, i.e. if the
1457
    /// target is a register rather than a single qubit.  This assumes that the `reset` token is
1458
    /// still in the token stream.
1459
    fn parse_reset(
42✔
1460
        &mut self,
42✔
1461
        bc: &mut Vec<Option<InternalBytecode>>,
42✔
1462
        condition: Option<Condition>,
42✔
1463
    ) -> PyResult<usize> {
42✔
1464
        let reset_token = self.expect_known(TokenType::Reset);
42✔
1465
        let qarg = self.require_qarg(&reset_token)?;
42✔
1466
        self.expect(TokenType::Semicolon, "';'", &reset_token)?;
28✔
1467
        if let Some(Condition { creg, value }) = condition {
16✔
1468
            match qarg {
10✔
1469
                Operand::Single(qubit) => {
4✔
1470
                    bc.push(Some(InternalBytecode::ConditionedReset {
4✔
1471
                        qubit,
4✔
1472
                        creg,
4✔
1473
                        value,
4✔
1474
                    }));
4✔
1475
                    Ok(1)
4✔
1476
                }
1477
                Operand::Range(size, start) => {
6✔
1478
                    bc.extend((0..size).map(|offset| {
8✔
1479
                        Some(InternalBytecode::ConditionedReset {
8✔
1480
                            qubit: start + offset,
8✔
1481
                            creg,
8✔
1482
                            value: value.clone(),
8✔
1483
                        })
8✔
1484
                    }));
8✔
1485
                    Ok(size)
6✔
1486
                }
1487
            }
1488
        } else {
1489
            match qarg {
6✔
1490
                Operand::Single(qubit) => {
2✔
1491
                    bc.push(Some(InternalBytecode::Reset { qubit }));
2✔
1492
                    Ok(0)
2✔
1493
                }
1494
                Operand::Range(size, start) => {
4✔
1495
                    bc.extend((0..size).map(|offset| {
4✔
1496
                        Some(InternalBytecode::Reset {
4✔
1497
                            qubit: start + offset,
4✔
1498
                        })
4✔
1499
                    }));
4✔
1500
                    Ok(size)
4✔
1501
                }
1502
            }
1503
        }
1504
    }
42✔
1505

1506
    /// Parse a declaration of a classical register, emitting the relevant bytecode and adding the
1507
    /// definition to the relevant parts of the internal symbol tables in the parser state.  This
1508
    /// assumes that the `creg` token is still in the token stream.
1509
    fn parse_creg(&mut self, bc: &mut Vec<Option<InternalBytecode>>) -> PyResult<usize> {
1,086✔
1510
        let creg_token = self.expect_known(TokenType::Creg);
1,086✔
1511
        let name_token = self.expect(TokenType::Id, "a valid identifier", &creg_token)?;
1,086✔
1512
        let name = name_token.id(&self.context);
1,084✔
1513
        let lbracket_token = self.expect(TokenType::LBracket, "'['", &creg_token)?;
1,084✔
1514
        let size = self
1,080✔
1515
            .expect(TokenType::Integer, "an integer", &lbracket_token)?
1,080✔
1516
            .int(&self.context);
1,078✔
1517
        self.expect(TokenType::RBracket, "']'", &lbracket_token)?;
1,078✔
1518
        self.expect(TokenType::Semicolon, "';'", &creg_token)?;
1,070✔
1519
        let symbol = GlobalSymbol::Creg {
1,064✔
1520
            size,
1,064✔
1521
            start: ClbitId::new(self.num_clbits),
1,064✔
1522
            index: CregId::new(self.num_cregs),
1,064✔
1523
        };
1,064✔
1524
        if self.symbols.insert(name.clone(), symbol).is_none() {
1,064✔
1525
            self.num_clbits += size;
1,054✔
1526
            self.num_cregs += 1;
1,054✔
1527
            bc.push(Some(InternalBytecode::DeclareCreg { name, size }));
1,054✔
1528
            Ok(1)
1,054✔
1529
        } else {
1530
            Err(QASM2ParseError::new_err(message_generic(
10✔
1531
                Some(&Position::new(
10✔
1532
                    self.current_filename(),
10✔
1533
                    name_token.line,
10✔
1534
                    name_token.col,
10✔
1535
                )),
10✔
1536
                &format!("'{}' is already defined", name_token.id(&self.context)),
10✔
1537
            )))
10✔
1538
        }
1539
    }
1,086✔
1540

1541
    /// Parse a declaration of a quantum register, emitting the relevant bytecode and adding the
1542
    /// definition to the relevant parts of the internal symbol tables in the parser state.  This
1543
    /// assumes that the `qreg` token is still in the token stream.
1544
    fn parse_qreg(&mut self, bc: &mut Vec<Option<InternalBytecode>>) -> PyResult<usize> {
1,314✔
1545
        let qreg_token = self.expect_known(TokenType::Qreg);
1,314✔
1546
        let name_token = self.expect(TokenType::Id, "a valid identifier", &qreg_token)?;
1,314✔
1547
        let name = name_token.id(&self.context);
1,308✔
1548
        let lbracket_token = self.expect(TokenType::LBracket, "'['", &qreg_token)?;
1,308✔
1549
        let size = self
1,302✔
1550
            .expect(TokenType::Integer, "an integer", &lbracket_token)?
1,302✔
1551
            .int(&self.context);
1,288✔
1552
        self.expect(TokenType::RBracket, "']'", &lbracket_token)?;
1,288✔
1553
        self.expect(TokenType::Semicolon, "';'", &qreg_token)?;
1,286✔
1554
        let symbol = GlobalSymbol::Qreg {
1,282✔
1555
            size,
1,282✔
1556
            start: QubitId::new(self.num_qubits),
1,282✔
1557
        };
1,282✔
1558
        if self.symbols.insert(name.clone(), symbol).is_none() {
1,282✔
1559
            self.num_qubits += size;
1,272✔
1560
            bc.push(Some(InternalBytecode::DeclareQreg { name, size }));
1,272✔
1561
            Ok(1)
1,272✔
1562
        } else {
1563
            Err(QASM2ParseError::new_err(message_generic(
10✔
1564
                Some(&Position::new(
10✔
1565
                    self.current_filename(),
10✔
1566
                    name_token.line,
10✔
1567
                    name_token.col,
10✔
1568
                )),
10✔
1569
                &format!("'{}' is already defined", name_token.id(&self.context)),
10✔
1570
            )))
10✔
1571
        }
1572
    }
1,314✔
1573

1574
    /// Parse an include statement.  This currently only actually handles includes of `qelib1.inc`,
1575
    /// which aren't actually parsed; the parser has a built-in version of the file that it simply
1576
    /// updates its state with (and the Python side of the parser does the same) rather than
1577
    /// re-parsing the same file every time.  This assumes that the `include` token is still in the
1578
    /// token stream.
1579
    fn parse_include(&mut self, bc: &mut Vec<Option<InternalBytecode>>) -> PyResult<usize> {
390✔
1580
        let include_token = self.expect_known(TokenType::Include);
390✔
1581
        let filename_token =
376✔
1582
            self.expect(TokenType::Filename, "a filename string", &include_token)?;
390✔
1583
        self.expect(TokenType::Semicolon, "';'", &include_token)?;
376✔
1584
        let filename = filename_token.filename(&self.context);
366✔
1585
        if filename == "qelib1.inc" {
366✔
1586
            self.symbols.reserve(QELIB1.len());
346✔
1587
            let mut indices = Vec::with_capacity(QELIB1.len());
346✔
1588
            for (i, (name, num_params, num_qubits)) in QELIB1.iter().enumerate() {
7,958✔
1589
                if self.define_gate(
7,958✔
1590
                    Some(&include_token),
7,958✔
1591
                    name.to_string(),
7,958✔
1592
                    *num_params,
7,958✔
1593
                    *num_qubits,
7,958✔
1594
                )? {
7,958✔
1595
                    indices.push(i);
7,958✔
1596
                }
7,958✔
1597
            }
1598
            bc.push(Some(InternalBytecode::SpecialInclude { indices }));
346✔
1599
            Ok(1)
346✔
1600
        } else {
1601
            let base_filename = std::path::PathBuf::from(&filename);
20✔
1602
            let absolute_filename = find_include_path(&base_filename, &self.include_path)
20✔
1603
                .ok_or_else(|| {
20✔
1604
                    QASM2ParseError::new_err(message_generic(
2✔
1605
                        Some(&Position::new(
2✔
1606
                            self.current_filename(),
2✔
1607
                            filename_token.line,
2✔
1608
                            filename_token.col,
2✔
1609
                        )),
2✔
1610
                        &format!(
2✔
1611
                            "unable to find '{}' in the include search path",
2✔
1612
                            base_filename.display()
2✔
1613
                        ),
2✔
1614
                    ))
2✔
1615
                })?;
20✔
1616
            let new_stream =
18✔
1617
                TokenStream::from_path(absolute_filename, self.strict).map_err(|err| {
18✔
1618
                    QASM2ParseError::new_err(message_generic(
×
1619
                        Some(&Position::new(
×
1620
                            self.current_filename(),
×
1621
                            filename_token.line,
×
1622
                            filename_token.col,
×
1623
                        )),
×
1624
                        &format!("unable to open file '{}' for reading: {}", &filename, err),
×
1625
                    ))
×
1626
                })?;
18✔
1627
            self.tokens.push(new_stream);
18✔
1628
            self.allow_version = true;
18✔
1629
            Ok(0)
18✔
1630
        }
1631
    }
390✔
1632

1633
    /// Update the parser state with the definition of a particular gate.  This does not emit any
1634
    /// bytecode because not all gate definitions need something passing to Python.  For example,
1635
    /// the Python parser initializes its state including the built-in gates `U` and `CX`, and
1636
    /// handles the `qelib1.inc` include specially as well.
1637
    fn define_gate(
10,772✔
1638
        &mut self,
10,772✔
1639
        owner: Option<&Token>,
10,772✔
1640
        name: String,
10,772✔
1641
        num_params: usize,
10,772✔
1642
        num_qubits: usize,
10,772✔
1643
    ) -> PyResult<bool> {
10,772✔
1644
        let already_defined = |state: &Self, name: String| {
10,772✔
1645
            let pos = owner.map(|tok| Position::new(state.current_filename(), tok.line, tok.col));
16✔
1646
            Err(QASM2ParseError::new_err(message_generic(
16✔
1647
                pos.as_ref(),
16✔
1648
                &format!("'{}' is already defined", name),
16✔
1649
            )))
16✔
1650
        };
16✔
1651
        let mismatched_definitions = |state: &Self, name: String, previous: OverridableGate| {
10,772✔
1652
            let plural = |count: usize, singular: &str| {
80✔
1653
                let mut out = format!("{} {}", count, singular);
80✔
1654
                if count != 1 {
80✔
1655
                    out.push('s');
26✔
1656
                }
54✔
1657
                out
80✔
1658
            };
80✔
1659
            let from_custom = format!(
20✔
1660
                "{} and {}",
20✔
1661
                plural(previous.num_params, "parameter"),
20✔
1662
                plural(previous.num_qubits, "qubit")
20✔
1663
            );
20✔
1664
            let from_program = format!(
20✔
1665
                "{} and {}",
20✔
1666
                plural(num_params, "parameter"),
20✔
1667
                plural(num_qubits, "qubit")
20✔
1668
            );
20✔
1669
            let pos = owner.map(|tok| Position::new(state.current_filename(), tok.line, tok.col));
20✔
1670
            Err(QASM2ParseError::new_err(message_generic(
20✔
1671
                pos.as_ref(),
20✔
1672
                &format!(
20✔
1673
                    concat!(
20✔
1674
                        "custom instruction '{}' is mismatched with its definition: ",
20✔
1675
                        "OpenQASM program has {}, custom has {}",
20✔
1676
                    ),
20✔
1677
                    name, from_program, from_custom
20✔
1678
                ),
20✔
1679
            )))
20✔
1680
        };
20✔
1681

1682
        if let Some(symbol) = self.overridable_gates.remove(&name) {
10,772✔
1683
            if num_params != symbol.num_params || num_qubits != symbol.num_qubits {
3,696✔
1684
                return mismatched_definitions(self, name, symbol);
20✔
1685
            }
3,676✔
1686
            match self.symbols.get(&name) {
3,676✔
1687
                None => {
1688
                    self.symbols.insert(name, symbol.into());
3,652✔
1689
                    self.num_gates += 1;
3,652✔
1690
                    Ok(true)
3,652✔
1691
                }
1692
                Some(GlobalSymbol::Gate { .. }) => {
1693
                    self.symbols.insert(name, symbol.into());
24✔
1694
                    Ok(false)
24✔
1695
                }
1696
                _ => already_defined(self, name),
×
1697
            }
1698
        } else if self.symbols.contains_key(&name) {
7,076✔
1699
            already_defined(self, name)
16✔
1700
        } else {
1701
            self.symbols.insert(
7,060✔
1702
                name,
7,060✔
1703
                GlobalSymbol::Gate {
7,060✔
1704
                    num_params,
7,060✔
1705
                    num_qubits,
7,060✔
1706
                    index: GateId::new(self.num_gates),
7,060✔
1707
                },
7,060✔
1708
            );
7,060✔
1709
            self.num_gates += 1;
7,060✔
1710
            Ok(true)
7,060✔
1711
        }
1712
    }
10,772✔
1713

1714
    /// Parse the next OpenQASM 2 statement in the program into a series of bytecode instructions.
1715
    ///
1716
    /// This is the principal public worker function of the parser.  One call to this function
1717
    /// parses a single OpenQASM 2 statement, which may expand to several bytecode instructions if
1718
    /// there is any broadcasting to resolve, or if the statement is a gate definition.  A call to
1719
    /// this function that returns `Some` will always have pushed at least one instruction to the
1720
    /// bytecode stream (the number is included).  A return of `None` signals the end of the
1721
    /// iterator.
1722
    pub fn parse_next(
6,704✔
1723
        &mut self,
6,704✔
1724
        bc: &mut Vec<Option<InternalBytecode>>,
6,704✔
1725
    ) -> PyResult<Option<usize>> {
6,704✔
1726
        if self.strict && self.allow_version {
6,704✔
1727
            match self.peek_token()?.map(|tok| tok.ttype) {
46✔
1728
                Some(TokenType::OpenQASM) => self.parse_version(),
42✔
1729
                Some(_) => {
1730
                    let token = self.next_token()?.unwrap();
2✔
1731
                    Err(QASM2ParseError::new_err(message_generic(
2✔
1732
                        Some(&Position::new(
2✔
1733
                            self.current_filename(),
2✔
1734
                            token.line,
2✔
1735
                            token.col,
2✔
1736
                        )),
2✔
1737
                        "[strict] the first statement must be 'OPENQASM 2.0;'",
2✔
1738
                    )))
2✔
1739
                }
1740
                None => Err(QASM2ParseError::new_err(message_generic(
2✔
1741
                    None,
2✔
1742
                    "[strict] saw an empty token stream, but needed a version statement",
2✔
1743
                ))),
2✔
1744
            }?;
4✔
1745
            self.allow_version = false;
42✔
1746
        }
6,658✔
1747
        let allow_version = self.allow_version;
6,700✔
1748
        self.allow_version = false;
6,700✔
1749
        while let Some(ttype) = self.peek_token()?.map(|tok| tok.ttype) {
7,348✔
1750
            let emitted = match ttype {
6,808✔
1751
                TokenType::Id => self.parse_gate_application(bc, None, false)?,
2,108✔
1752
                TokenType::Creg => self.parse_creg(bc)?,
1,086✔
1753
                TokenType::Qreg => self.parse_qreg(bc)?,
1,314✔
1754
                TokenType::Include => self.parse_include(bc)?,
390✔
1755
                TokenType::Measure => self.parse_measure(bc, None)?,
430✔
1756
                TokenType::Reset => self.parse_reset(bc, None)?,
32✔
1757
                TokenType::Barrier => self.parse_barrier(bc, None)?,
176✔
1758
                TokenType::If => self.parse_conditional(bc)?,
280✔
1759
                TokenType::Opaque => self.parse_opaque_definition(bc)?,
100✔
1760
                TokenType::Gate => self.parse_gate_definition(bc)?,
288✔
1761
                TokenType::OpenQASM => {
1762
                    if allow_version {
584✔
1763
                        self.parse_version()?
582✔
1764
                    } else {
1765
                        let token = self.next_token()?.unwrap();
2✔
1766
                        return Err(QASM2ParseError::new_err(message_generic(
2✔
1767
                            Some(&Position::new(
2✔
1768
                                self.current_filename(),
2✔
1769
                                token.line,
2✔
1770
                                token.col,
2✔
1771
                            )),
2✔
1772
                            "only the first statement may be a version declaration",
2✔
1773
                        )));
2✔
1774
                    }
1775
                }
1776
                TokenType::Semicolon => {
1777
                    let token = self.next_token()?.unwrap();
18✔
1778
                    if self.strict {
18✔
1779
                        return Err(QASM2ParseError::new_err(message_generic(
4✔
1780
                            Some(&Position::new(
4✔
1781
                                self.current_filename(),
4✔
1782
                                token.line,
4✔
1783
                                token.col,
4✔
1784
                            )),
4✔
1785
                            "[strict] empty statements and/or extra semicolons are forbidden",
4✔
1786
                        )));
4✔
1787
                    } else {
1788
                        0
14✔
1789
                    }
1790
                }
1791
                _ => {
1792
                    let token = self.next_token()?.unwrap();
2✔
1793
                    return Err(QASM2ParseError::new_err(message_generic(
2✔
1794
                        Some(&Position::new(
2✔
1795
                            self.current_filename(),
2✔
1796
                            token.line,
2✔
1797
                            token.col,
2✔
1798
                        )),
2✔
1799
                        &format!(
2✔
1800
                            "needed a start-of-statement token, but instead got {}",
2✔
1801
                            token.text(&self.context)
2✔
1802
                        ),
2✔
1803
                    )));
2✔
1804
                }
1805
            };
1806
            if emitted > 0 {
6,086✔
1807
                return Ok(Some(emitted));
5,438✔
1808
            }
648✔
1809
        }
1810
        Ok(None)
516✔
1811
    }
6,704✔
1812
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2024 Coveralls, Inc