microsoft/qdk

Public

mirrored from https://github.com/microsoft/qdkAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
5202db92bb89d9165553a3e17d59ec79255406f2

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

source/compiler/qsc_eval/src/lib.rs

2292lines · modecode

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! The Q# evaluator handles the execution of Q# programs and/or fragments.
5//! It operates based on vectors of `ExecGraphNode` instances, which act as a control flow graph
6//! and are generated by lowering to FIR. The evaluator will iterate through the given graph,
7//! executing the instructions it encounters and updating the state it was given accordingly, and using
8//! the FIR store to look up graphs for any called functions or operations. The evaluator handles tracking
9//! of stack frames and push/pop of variable scopes, and uses the index into the current execution graph
10//! as a kind of stack pointer, updating the index based on `Jump`, `JumpIf`, and `JumpIfNot` instructions.
11//!
12//! Of note, the evaluator does not own the program state, which is tracked by the passed in `Env`
13//! and `Backend` instances. This allows the evaluator to be reentrant, and supports both whole-program,
14//! effectively stateless execution (like running shots of a program) stateful execution scenarios
15//! (like debugging or notebooks).
16
17#[cfg(test)]
18mod tests;
19
20pub mod backend;
21pub mod debug;
22mod error;
23pub mod intrinsic;
24pub mod noise;
25pub mod output;
26pub mod state;
27pub mod val;
28
29use crate::val::{
30 Value, index_array, make_range, slice_array, update_index_range, update_index_single,
31};
32use backend::Backend;
33use debug::{CallStack, Frame};
34pub use error::PackageSpan;
35use miette::Diagnostic;
36use num_bigint::BigInt;
37use output::Receiver;
38use qsc_data_structures::{functors::FunctorApp, index_map::IndexMap, span::Span};
39use qsc_fir::fir::{
40 self, BinOp, BlockId, CallableImpl, ExecGraph, ExecGraphNode, Expr, ExprId, ExprKind, Field,
41 FieldAssign, Global, Lit, LocalItemId, LocalVarId, PackageId, PackageStoreLookup, PatId,
42 PatKind, PrimField, Res, StmtId, StoreItemId, StringComponent, UnOp,
43};
44use qsc_fir::ty::Ty;
45use qsc_lowerer::map_fir_package_to_hir;
46use rand::{SeedableRng, rngs::StdRng};
47use rustc_hash::{FxHashMap, FxHashSet};
48use std::ops;
49use std::{
50 cell::RefCell,
51 fmt::{self, Display, Formatter},
52 iter,
53 ops::Neg,
54 rc::Rc,
55};
56use thiserror::Error;
57use val::{Qubit, update_functor_app};
58
59#[derive(Clone, Debug, Diagnostic, Error)]
60pub enum Error {
61 #[error("array too large")]
62 #[diagnostic(code("Qsc.Eval.ArrayTooLarge"))]
63 ArrayTooLarge(#[label("this array has too many items")] PackageSpan),
64
65 #[error("callable already counted")]
66 #[diagnostic(help(
67 "counting for a given callable must be stopped before it can be started again"
68 ))]
69 #[diagnostic(code("Qsc.Eval.CallableAlreadyCounted"))]
70 CallableAlreadyCounted(#[label] PackageSpan),
71
72 #[error("callable not counted")]
73 #[diagnostic(help("counting for a given callable must be started before it can be stopped"))]
74 #[diagnostic(code("Qsc.Eval.CallableNotCounted"))]
75 CallableNotCounted(#[label] PackageSpan),
76
77 #[error("invalid array length: {0}")]
78 #[diagnostic(code("Qsc.Eval.InvalidArrayLength"))]
79 InvalidArrayLength(i64, #[label("cannot be used as a length")] PackageSpan),
80
81 #[error("division by zero")]
82 #[diagnostic(code("Qsc.Eval.DivZero"))]
83 DivZero(#[label("cannot divide by zero")] PackageSpan),
84
85 #[error("empty range")]
86 #[diagnostic(code("Qsc.Eval.EmptyRange"))]
87 EmptyRange(#[label("the range cannot be empty")] PackageSpan),
88
89 #[error("value cannot be used as an index: {0}")]
90 #[diagnostic(code("Qsc.Eval.InvalidIndex"))]
91 InvalidIndex(i64, #[label("invalid index")] PackageSpan),
92
93 #[error("integer too large for operation")]
94 #[diagnostic(code("Qsc.Eval.IntTooLarge"))]
95 IntTooLarge(i64, #[label("this value is too large")] PackageSpan),
96
97 #[error("index out of range: {0}")]
98 #[diagnostic(code("Qsc.Eval.IndexOutOfRange"))]
99 IndexOutOfRange(i64, #[label("out of range")] PackageSpan),
100
101 #[error("intrinsic callable `{0}` failed: {1}")]
102 #[diagnostic(code("Qsc.Eval.IntrinsicFail"))]
103 IntrinsicFail(String, String, #[label] PackageSpan),
104
105 #[error("invalid rotation angle: {0}")]
106 #[diagnostic(code("Qsc.Eval.InvalidRotationAngle"))]
107 InvalidRotationAngle(f64, #[label("invalid rotation angle")] PackageSpan),
108
109 #[error("negative integers cannot be used here: {0}")]
110 #[diagnostic(code("Qsc.Eval.InvalidNegativeInt"))]
111 InvalidNegativeInt(i64, #[label("invalid negative integer")] PackageSpan),
112
113 #[error("output failure")]
114 #[diagnostic(code("Qsc.Eval.OutputFail"))]
115 OutputFail(#[label("failed to generate output")] PackageSpan),
116
117 #[error("qubits in invocation are not unique")]
118 #[diagnostic(code("Qsc.Eval.QubitUniqueness"))]
119 QubitUniqueness(#[label] PackageSpan),
120
121 #[error("qubit used after release")]
122 #[diagnostic(help(
123 "qubits should not be used after being released, which typically occurs when a qubit is used after it has gone out of scope"
124 ))]
125 #[diagnostic(code("Qsc.Eval.QubitUsedAfterRelease"))]
126 QubitUsedAfterRelease(#[label] PackageSpan),
127
128 #[error("qubit double release")]
129 #[diagnostic(code("Qsc.Eval.QubitDoubleRelease"))]
130 QubitDoubleRelease(#[label("qubit has already been released")] PackageSpan),
131
132 #[error("qubits already counted")]
133 #[diagnostic(help("counting for qubits must be stopped before it can be started again"))]
134 #[diagnostic(code("Qsc.Eval.QubitsAlreadyCounted"))]
135 QubitsAlreadyCounted(#[label] PackageSpan),
136
137 #[error("qubits not counted")]
138 #[diagnostic(help("counting for qubits must be started before it can be stopped"))]
139 #[diagnostic(code("Qsc.Eval.QubitsNotCounted"))]
140 QubitsNotCounted(#[label] PackageSpan),
141
142 #[error("qubits are not separable")]
143 #[diagnostic(help(
144 "subset of qubits provided as arguments must not be entangled with any qubits outside of the subset"
145 ))]
146 #[diagnostic(code("Qsc.Eval.QubitsNotSeparable"))]
147 QubitsNotSeparable(#[label] PackageSpan),
148
149 #[error("range with step size of zero")]
150 #[diagnostic(code("Qsc.Eval.RangeStepZero"))]
151 RangeStepZero(#[label("invalid range")] PackageSpan),
152
153 #[error("qubit arrays used in relabeling must be a permutation of the same set of qubits")]
154 #[diagnostic(help("ensure that each qubit is present exactly once in both arrays"))]
155 #[diagnostic(code("Qsc.Eval.RelabelingMismatch"))]
156 RelabelingMismatch(#[label] PackageSpan),
157
158 #[error("Qubit{0} released while not in |0⟩ state")]
159 #[diagnostic(help(
160 "qubits should be returned to the |0⟩ state before being released to satisfy the assumption that allocated qubits start in the |0⟩ state"
161 ))]
162 #[diagnostic(code("Qsc.Eval.ReleasedQubitNotZero"))]
163 ReleasedQubitNotZero(usize, #[label("Qubit{0}")] PackageSpan),
164
165 #[error("cannot compare measurement results")]
166 #[diagnostic(code("Qsc.Eval.ResultComparisonUnsupported"))]
167 #[diagnostic(help(
168 "comparing measurement results is not supported when performing circuit synthesis or base profile QIR generation"
169 ))]
170 ResultComparisonUnsupported(#[label("cannot compare to result")] PackageSpan),
171
172 #[error("cannot compare measurement result from qubit loss")]
173 #[diagnostic(code("Qsc.Eval.ResultLossComparisonUnsupported"))]
174 #[diagnostic(help(
175 "use of a measurement result from a qubit that was lost is not supported, use `IsLossResult` to ensure the result is valid before using it in a comparison"
176 ))]
177 ResultLossComparisonUnsupported(#[label("cannot compare result from qubit loss")] PackageSpan),
178
179 #[error("name is not bound")]
180 #[diagnostic(code("Qsc.Eval.UnboundName"))]
181 UnboundName(#[label] PackageSpan),
182
183 #[error("unknown intrinsic `{0}`")]
184 #[diagnostic(code("Qsc.Eval.UnknownIntrinsic"))]
185 UnknownIntrinsic(
186 String,
187 #[label("callable has no implementation")] PackageSpan,
188 ),
189
190 #[error("unsupported return type for intrinsic `{0}`")]
191 #[diagnostic(help("intrinsic callable return type should be `Unit`"))]
192 #[diagnostic(code("Qsc.Eval.UnsupportedIntrinsicType"))]
193 UnsupportedIntrinsicType(String, #[label] PackageSpan),
194
195 #[error("program failed: {0}")]
196 #[diagnostic(code("Qsc.Eval.UserFail"))]
197 UserFail(String, #[label("explicit fail")] PackageSpan),
198}
199
200impl Error {
201 #[must_use]
202 pub fn span(&self) -> &PackageSpan {
203 match self {
204 Error::ArrayTooLarge(span)
205 | Error::CallableAlreadyCounted(span)
206 | Error::CallableNotCounted(span)
207 | Error::DivZero(span)
208 | Error::EmptyRange(span)
209 | Error::IndexOutOfRange(_, span)
210 | Error::InvalidIndex(_, span)
211 | Error::IntrinsicFail(_, _, span)
212 | Error::IntTooLarge(_, span)
213 | Error::InvalidRotationAngle(_, span)
214 | Error::InvalidNegativeInt(_, span)
215 | Error::OutputFail(span)
216 | Error::QubitUniqueness(span)
217 | Error::QubitUsedAfterRelease(span)
218 | Error::QubitDoubleRelease(span)
219 | Error::QubitsAlreadyCounted(span)
220 | Error::QubitsNotCounted(span)
221 | Error::QubitsNotSeparable(span)
222 | Error::RangeStepZero(span)
223 | Error::RelabelingMismatch(span)
224 | Error::ReleasedQubitNotZero(_, span)
225 | Error::ResultComparisonUnsupported(span)
226 | Error::ResultLossComparisonUnsupported(span)
227 | Error::UnboundName(span)
228 | Error::UnknownIntrinsic(_, span)
229 | Error::UnsupportedIntrinsicType(_, span)
230 | Error::UserFail(_, span)
231 | Error::InvalidArrayLength(_, span) => span,
232 }
233 }
234}
235
236/// A specialization that may be implemented for an operation.
237enum Spec {
238 /// The default specialization.
239 Body,
240 /// The adjoint specialization.
241 Adj,
242 /// The controlled specialization.
243 Ctl,
244 /// The controlled adjoint specialization.
245 CtlAdj,
246}
247
248impl Display for Spec {
249 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
250 match self {
251 Spec::Body => f.write_str("body"),
252 Spec::Adj => f.write_str("adjoint"),
253 Spec::Ctl => f.write_str("controlled"),
254 Spec::CtlAdj => f.write_str("controlled adjoint"),
255 }
256 }
257}
258
259/// Utility function to identify a subset of a control flow graph corresponding to a given
260/// range.
261#[must_use]
262pub fn exec_graph_section(graph: &ExecGraph, range: ops::Range<usize>) -> ExecGraph {
263 let start: u32 = range
264 .start
265 .try_into()
266 .expect("exec graph ranges should fit into u32");
267 graph[range]
268 .iter()
269 .map(|node| match node {
270 ExecGraphNode::Jump(idx) => ExecGraphNode::Jump(idx - start),
271 ExecGraphNode::JumpIf(idx) => ExecGraphNode::JumpIf(idx - start),
272 ExecGraphNode::JumpIfNot(idx) => ExecGraphNode::JumpIfNot(idx - start),
273 _ => *node,
274 })
275 .collect::<Vec<_>>()
276 .into()
277}
278
279/// Evaluates the given code with the given context.
280/// # Errors
281/// Returns the first error encountered during execution.
282/// # Panics
283/// On internal error where no result is returned.
284pub fn eval(
285 package: PackageId,
286 seed: Option<u64>,
287 exec_graph: ExecGraph,
288 globals: &impl PackageStoreLookup,
289 env: &mut Env,
290 sim: &mut impl Backend<ResultType = impl Into<val::Result>>,
291 receiver: &mut impl Receiver,
292) -> Result<Value, (Error, Vec<Frame>)> {
293 let mut state = State::new(package, exec_graph, seed, ErrorBehavior::FailOnError);
294 let res = state.eval(globals, env, sim, receiver, &[], StepAction::Continue)?;
295 let StepResult::Return(value) = res else {
296 panic!("eval should always return a value");
297 };
298 Ok(value)
299}
300
301/// Evaluates the given callable with the given context.
302/// # Errors
303/// Returns the first error encountered during execution.
304/// # Panics
305/// On internal error where no result is returned.
306#[allow(clippy::too_many_arguments)]
307pub fn invoke(
308 package: PackageId,
309 seed: Option<u64>,
310 globals: &impl PackageStoreLookup,
311 env: &mut Env,
312 sim: &mut impl Backend<ResultType = impl Into<val::Result>>,
313 receiver: &mut impl Receiver,
314 callable: Value,
315 args: Value,
316) -> Result<Value, (Error, Vec<Frame>)> {
317 let mut state = State::new(package, Vec::new().into(), seed, ErrorBehavior::FailOnError);
318 // Push the callable value into the state stack and then the args value so they are ready for evaluation.
319 state.set_val_register(callable);
320 state.push_val();
321 state.set_val_register(args);
322
323 // Evaluate the call, which will pop the args and callable values from the stack and then either
324 // a) prepare the call stack for the execution of the callable, or
325 // b) invoke the callable directly if it is an intrinsic.
326 state
327 .eval_call(
328 env,
329 sim,
330 globals,
331 Span::default(),
332 Span::default(),
333 receiver,
334 )
335 .map_err(|e| (e, state.get_stack_frames()))?;
336
337 // Trigger evaluation of the state until the end of the stack is reached and a return value is obtained, which will be the final
338 // result of the invocation.
339 let res = state.eval(globals, env, sim, receiver, &[], StepAction::Continue)?;
340 let StepResult::Return(value) = res else {
341 panic!("eval should always return a value");
342 };
343 Ok(value)
344}
345
346/// The type of step action to take during evaluation
347#[derive(Debug, Copy, Clone, Eq, PartialEq)]
348pub enum StepAction {
349 Next,
350 In,
351 Out,
352 Continue,
353}
354
355// The result of an evaluation step.
356#[derive(Clone, Debug)]
357pub enum StepResult {
358 BreakpointHit(StmtId),
359 Next,
360 StepIn,
361 StepOut,
362 Return(Value),
363 Fail(String),
364}
365
366trait AsIndex {
367 type Output;
368
369 fn as_index(&self, index_source: PackageSpan) -> Self::Output;
370}
371
372impl AsIndex for i64 {
373 type Output = Result<usize, Error>;
374
375 fn as_index(&self, index_source: PackageSpan) -> Self::Output {
376 match (*self).try_into() {
377 Ok(index) => Ok(index),
378 Err(_) => Err(Error::InvalidIndex(*self, index_source)),
379 }
380 }
381}
382
383#[derive(Debug, Clone)]
384pub struct Variable {
385 pub name: Rc<str>,
386 pub value: Value,
387 pub span: Span,
388}
389
390#[derive(Debug, Clone)]
391pub struct VariableInfo {
392 pub value: Value,
393 pub name: Rc<str>,
394 pub type_name: String,
395 pub span: Span,
396}
397
398pub struct Range {
399 step: i64,
400 end: i64,
401 curr: i64,
402}
403
404impl Iterator for Range {
405 type Item = i64;
406
407 fn next(&mut self) -> Option<Self::Item> {
408 let curr = self.curr;
409 self.curr += self.step;
410 if (self.step > 0 && curr <= self.end) || (self.step < 0 && curr >= self.end) {
411 Some(curr)
412 } else {
413 None
414 }
415 }
416}
417
418impl Range {
419 fn new(start: i64, step: i64, end: i64) -> Self {
420 Range {
421 step,
422 end,
423 curr: start,
424 }
425 }
426}
427
428pub struct Env {
429 scopes: Vec<Scope>,
430 qubits: FxHashSet<Rc<Qubit>>,
431}
432
433impl Default for Env {
434 fn default() -> Self {
435 // Always create a global scope for top-level statements.
436 Self {
437 scopes: vec![Scope::default()],
438 qubits: FxHashSet::default(),
439 }
440 }
441}
442
443impl Env {
444 #[must_use]
445 pub fn get(&self, id: LocalVarId) -> Option<&Variable> {
446 self.scopes
447 .iter()
448 .rev()
449 .find_map(|scope| scope.bindings.get(id))
450 }
451
452 fn get_mut(&mut self, id: LocalVarId) -> Option<&mut Variable> {
453 self.scopes
454 .iter_mut()
455 .rev()
456 .find_map(|scope| scope.bindings.get_mut(id))
457 }
458
459 pub fn push_scope(&mut self, frame_id: usize) {
460 let scope = Scope {
461 frame_id,
462 ..Default::default()
463 };
464 self.scopes.push(scope);
465 }
466
467 pub fn leave_scope(&mut self) {
468 // Only pop the scope if there is more than one scope in the stack,
469 // because the global/top-level scope cannot be exited.
470 if self.scopes.len() > 1 {
471 self.scopes
472 .pop()
473 .expect("scope should have more than one entry.");
474 }
475 }
476
477 pub fn leave_current_frame(&mut self) {
478 let current_frame_id = self
479 .scopes
480 .last()
481 .expect("should be at least one scope")
482 .frame_id;
483 if current_frame_id == 0 {
484 // Do not remove the global scope.
485 return;
486 }
487 self.scopes
488 .retain(|scope| scope.frame_id != current_frame_id);
489 }
490
491 pub fn bind_variable_in_top_frame(&mut self, local_var_id: LocalVarId, var: Variable) {
492 let Some(scope) = self.scopes.last_mut() else {
493 panic!("no frames in scope");
494 };
495
496 scope.bindings.insert(local_var_id, var);
497 }
498
499 #[must_use]
500 pub fn get_variables_in_top_frame(&self) -> Vec<VariableInfo> {
501 if let Some(scope) = self.scopes.last() {
502 self.get_variables_in_frame(scope.frame_id)
503 } else {
504 vec![]
505 }
506 }
507
508 #[must_use]
509 pub fn get_variables_in_frame(&self, frame_id: usize) -> Vec<VariableInfo> {
510 let candidate_scopes: Vec<_> = self
511 .scopes
512 .iter()
513 .filter(|scope| scope.frame_id == frame_id)
514 .map(|scope| scope.bindings.iter())
515 .collect();
516
517 let variables_by_scope: Vec<Vec<VariableInfo>> = candidate_scopes
518 .into_iter()
519 .map(|bindings| {
520 bindings
521 .map(|(_, var)| VariableInfo {
522 name: var.name.clone(),
523 type_name: var.value.type_name().to_string(),
524 value: var.value.clone(),
525 span: var.span,
526 })
527 .collect()
528 })
529 .collect();
530 variables_by_scope.into_iter().flatten().collect::<Vec<_>>()
531 }
532
533 #[allow(clippy::len_without_is_empty)]
534 #[must_use]
535 pub fn len(&self) -> usize {
536 self.scopes.len()
537 }
538
539 pub fn update_variable_in_top_frame(&mut self, local_var_id: LocalVarId, value: Value) {
540 let variable = self
541 .get_mut(local_var_id)
542 .expect("local variable is not present");
543 variable.value = value;
544 }
545
546 pub fn track_qubit(&mut self, qubit: Rc<Qubit>) {
547 self.qubits.insert(qubit);
548 }
549
550 pub fn release_qubit(&mut self, qubit: &Rc<Qubit>) {
551 self.qubits.remove(qubit);
552 }
553}
554
555#[derive(Default)]
556struct Scope {
557 bindings: IndexMap<LocalVarId, Variable>,
558 frame_id: usize,
559}
560
561type CallableCountKey = (StoreItemId, bool, bool);
562
563#[derive(Debug, Clone, Copy, Eq, PartialEq)]
564pub enum ErrorBehavior {
565 /// Fail execution if an error is encountered.
566 FailOnError,
567 /// Stop execution on the first error encountered.
568 StopOnError,
569}
570
571pub struct State {
572 exec_graph_stack: Vec<ExecGraph>,
573 idx: u32,
574 idx_stack: Vec<u32>,
575 val_register: Option<Value>,
576 val_stack: Vec<Vec<Value>>,
577 source_package: PackageId,
578 package: PackageId,
579 call_stack: CallStack,
580 current_span: Span,
581 rng: RefCell<StdRng>,
582 call_counts: FxHashMap<CallableCountKey, i64>,
583 qubit_counter: Option<QubitCounter>,
584 error_behavior: ErrorBehavior,
585 last_error: Option<(Error, Vec<Frame>)>,
586}
587
588impl State {
589 #[must_use]
590 pub fn new(
591 package: PackageId,
592 exec_graph: ExecGraph,
593 classical_seed: Option<u64>,
594 error_behavior: ErrorBehavior,
595 ) -> Self {
596 let rng = match classical_seed {
597 Some(seed) => RefCell::new(StdRng::seed_from_u64(seed)),
598 None => RefCell::new(StdRng::from_entropy()),
599 };
600 Self {
601 exec_graph_stack: vec![exec_graph],
602 idx: 0,
603 idx_stack: Vec::new(),
604 val_register: None,
605 val_stack: vec![Vec::new()],
606 source_package: package,
607 package,
608 call_stack: CallStack::default(),
609 current_span: Span::default(),
610 rng,
611 call_counts: FxHashMap::default(),
612 qubit_counter: None,
613 error_behavior,
614 last_error: None,
615 }
616 }
617
618 fn push_frame(&mut self, exec_graph: ExecGraph, id: StoreItemId, functor: FunctorApp) {
619 self.call_stack.push_frame(Frame {
620 span: self.current_span,
621 id,
622 caller: self.package,
623 functor,
624 });
625 self.exec_graph_stack.push(exec_graph);
626 self.val_stack.push(Vec::new());
627 self.idx_stack.push(self.idx);
628 self.idx = 0;
629 self.package = id.package;
630 }
631
632 fn leave_frame(&mut self) {
633 if let Some(frame) = self.call_stack.pop_frame() {
634 self.package = frame.caller;
635 }
636 self.val_stack.pop();
637 self.idx = self.idx_stack.pop().unwrap_or_default();
638 self.exec_graph_stack.pop();
639 }
640
641 fn push_scope(&mut self, env: &mut Env) {
642 // `push_frame`, which increments the length of `self.call_stack` by 1,
643 // is called before `self.push_scope`.
644 // Since the first `frame_id` should be 0, we substract 1 here.
645 env.push_scope(self.call_stack.len() - 1);
646 }
647
648 fn take_val_register(&mut self) -> Value {
649 self.val_register.take().expect("value should be present")
650 }
651
652 fn set_val_register(&mut self, val: Value) {
653 self.val_register = Some(val);
654 }
655
656 fn pop_val(&mut self) -> Value {
657 self.val_stack
658 .last_mut()
659 .expect("should have at least one value frame")
660 .pop()
661 .expect("value should be present")
662 }
663
664 fn pop_vals(&mut self, len: usize) -> Vec<Value> {
665 let last = self
666 .val_stack
667 .last_mut()
668 .expect("should have at least one value frame");
669 last.drain(last.len() - len..).collect()
670 }
671
672 fn push_val(&mut self) {
673 let val = self.take_val_register();
674 self.val_stack
675 .last_mut()
676 .expect("should have at least one value frame")
677 .push(val);
678 }
679
680 #[must_use]
681 pub fn get_stack_frames(&self) -> Vec<Frame> {
682 let mut frames = self.call_stack.clone().into_frames();
683
684 let mut span = self.current_span;
685 for frame in frames.iter_mut().rev() {
686 std::mem::swap(&mut frame.span, &mut span);
687 }
688 frames
689 }
690
691 fn set_last_error(&mut self, error: Error, frames: Vec<Frame>) {
692 assert!(
693 self.last_error.replace((error, frames)).is_none(),
694 "last error should not be set twice"
695 );
696 }
697
698 fn get_last_error(&mut self) -> Result<(), (Error, Vec<Frame>)> {
699 // Use `is_none` to check for last error, as it avoids the unconditional
700 // `mem::replace` call that `take` would perform.
701 if self.last_error.is_none() {
702 Ok(())
703 } else {
704 Err(self.last_error.take().expect("last error should be set"))
705 }
706 }
707
708 /// # Errors
709 /// Returns the first error encountered during execution.
710 /// # Panics
711 /// When returning a value in the middle of execution.
712 #[allow(clippy::too_many_lines)]
713 pub fn eval(
714 &mut self,
715 globals: &impl PackageStoreLookup,
716 env: &mut Env,
717 sim: &mut impl Backend<ResultType = impl Into<val::Result>>,
718 out: &mut impl Receiver,
719 breakpoints: &[StmtId],
720 step: StepAction,
721 ) -> Result<StepResult, (Error, Vec<Frame>)> {
722 let current_frame = self.call_stack.len();
723 while !self.exec_graph_stack.is_empty() {
724 let exec_graph = self
725 .exec_graph_stack
726 .last()
727 .expect("should have at least one stack frame");
728 let res = match exec_graph.get(self.idx as usize) {
729 Some(ExecGraphNode::Bind(pat)) => {
730 self.idx += 1;
731 self.eval_bind(env, globals, *pat);
732 continue;
733 }
734 Some(ExecGraphNode::Expr(expr)) => {
735 self.idx += 1;
736 match self.eval_expr(env, sim, globals, out, *expr) {
737 Ok(()) => continue,
738 Err(e) => {
739 if self.error_behavior == ErrorBehavior::StopOnError {
740 let error_str = e.to_string();
741 self.set_last_error(e, self.get_stack_frames());
742 // Clear the execution graph stack to indicate that execution has failed.
743 // This will prevent further execution steps.
744 self.exec_graph_stack.clear();
745 return Ok(StepResult::Fail(error_str));
746 }
747 return Err((e, self.get_stack_frames()));
748 }
749 }
750 }
751 Some(ExecGraphNode::Stmt(stmt)) => {
752 self.idx += 1;
753 self.current_span = globals.get_stmt((self.package, *stmt).into()).span;
754
755 match self.check_for_break(breakpoints, *stmt, step, current_frame) {
756 Some(value) => value,
757 None => continue,
758 }
759 }
760 Some(ExecGraphNode::Jump(idx)) => {
761 self.idx = *idx;
762 continue;
763 }
764 Some(ExecGraphNode::JumpIf(idx)) => {
765 let cond = self.val_register == Some(Value::Bool(true));
766 if cond {
767 self.idx = *idx;
768 } else {
769 self.idx += 1;
770 }
771 continue;
772 }
773 Some(ExecGraphNode::JumpIfNot(idx)) => {
774 let cond = self.val_register == Some(Value::Bool(true));
775 if cond {
776 self.idx += 1;
777 } else {
778 self.idx = *idx;
779 }
780 continue;
781 }
782 Some(ExecGraphNode::Store) => {
783 self.push_val();
784 self.idx += 1;
785 continue;
786 }
787 Some(ExecGraphNode::Unit) => {
788 self.idx += 1;
789 self.set_val_register(Value::unit());
790 continue;
791 }
792 Some(ExecGraphNode::Ret) => {
793 self.leave_frame();
794 env.leave_scope();
795 continue;
796 }
797 Some(ExecGraphNode::RetFrame) => {
798 self.leave_frame();
799 env.leave_current_frame();
800 continue;
801 }
802 Some(ExecGraphNode::PushScope) => {
803 self.push_scope(env);
804 self.idx += 1;
805 continue;
806 }
807 Some(ExecGraphNode::PopScope) => {
808 env.leave_scope();
809 self.idx += 1;
810 continue;
811 }
812 Some(ExecGraphNode::BlockEnd(id)) => {
813 self.idx += 1;
814 match self.check_for_block_exit_break(globals, *id, step, current_frame) {
815 Some((result, span)) => {
816 self.current_span = span;
817 return Ok(result);
818 }
819 None => continue,
820 }
821 }
822 None => {
823 // We have reached the end of the current graph without reaching an explicit return node,
824 // usually indicating the partial execution of a single sub-expression.
825 // This means we should pop the execution graph but not the current environment scope,
826 // so bound variables are still accessible after completion.
827 self.exec_graph_stack.pop();
828 assert!(self.exec_graph_stack.is_empty());
829 continue;
830 }
831 };
832
833 if let StepResult::Return(_) = res {
834 panic!("unexpected return");
835 }
836
837 return Ok(res);
838 }
839
840 // If we made it out of the execution loop, we either reached the end of the graph,
841 // a return expression, or hit a runtime error. Check here for the error case
842 // and return it if it exists.
843 self.get_last_error()?;
844
845 Ok(StepResult::Return(self.get_result()))
846 }
847
848 fn check_for_break(
849 &self,
850 breakpoints: &[StmtId],
851 stmt: StmtId,
852 step: StepAction,
853 current_frame: usize,
854 ) -> Option<StepResult> {
855 Some(
856 if let Some(bp) = breakpoints
857 .iter()
858 .find(|&bp| *bp == stmt && self.package == self.source_package)
859 {
860 StepResult::BreakpointHit(*bp)
861 } else {
862 if self.current_span == Span::default() {
863 // if there is no span, we are in generated code, so we should skip
864 return None;
865 }
866 // no breakpoint, but we may stop here
867 if step == StepAction::In {
868 StepResult::StepIn
869 } else if step == StepAction::Next && current_frame >= self.call_stack.len() {
870 StepResult::Next
871 } else if step == StepAction::Out && current_frame > self.call_stack.len() {
872 StepResult::StepOut
873 } else {
874 return None;
875 }
876 },
877 )
878 }
879
880 fn check_for_block_exit_break(
881 &self,
882 globals: &impl PackageStoreLookup,
883 block: BlockId,
884 step: StepAction,
885 current_frame: usize,
886 ) -> Option<(StepResult, Span)> {
887 if step == StepAction::Next && current_frame >= self.call_stack.len() {
888 let block = globals.get_block((self.package, block).into());
889 let span = Span {
890 lo: block.span.hi - 1,
891 hi: block.span.hi,
892 };
893 Some((StepResult::Next, span))
894 } else {
895 None
896 }
897 }
898
899 pub fn get_result(&mut self) -> Value {
900 // Some executions don't have any statements to execute,
901 // such as a fragment that has only item definitions.
902 // In that case, the values are empty and the result is unit.
903 self.val_register.take().unwrap_or_else(Value::unit)
904 }
905
906 #[allow(clippy::similar_names)]
907 fn eval_expr(
908 &mut self,
909 env: &mut Env,
910 sim: &mut impl Backend<ResultType = impl Into<val::Result>>,
911 globals: &impl PackageStoreLookup,
912 out: &mut impl Receiver,
913 expr: ExprId,
914 ) -> Result<(), Error> {
915 let expr = globals.get_expr((self.package, expr).into());
916 self.current_span = expr.span;
917 match &expr.kind {
918 ExprKind::Array(arr) => self.eval_arr(arr.len()),
919 ExprKind::ArrayLit(arr) => self.eval_arr_lit(arr, globals),
920 ExprKind::ArrayRepeat(..) => self.eval_arr_repeat(expr.span)?,
921 ExprKind::Assign(lhs, _) => self.eval_assign(env, globals, *lhs)?,
922 ExprKind::AssignOp(op, lhs, rhs) => {
923 let rhs_span = globals.get_expr((self.package, *rhs).into()).span;
924 let (is_array, is_unique) =
925 is_updatable_in_place(env, globals.get_expr((self.package, *lhs).into()));
926 if is_array {
927 if is_unique {
928 self.eval_array_append_in_place(env, globals, *lhs)?;
929 return Ok(());
930 }
931 let rhs_val = self.take_val_register();
932 self.eval_expr(env, sim, globals, out, *lhs)?;
933 self.push_val();
934 self.set_val_register(rhs_val);
935 }
936 self.eval_binop(*op, rhs_span)?;
937 self.eval_assign(env, globals, *lhs)?;
938 }
939 ExprKind::AssignField(record, field, _) => {
940 self.eval_update_field(field.clone());
941 self.eval_assign(env, globals, *record)?;
942 }
943 ExprKind::AssignIndex(lhs, mid, _) => {
944 let mid_span = globals.get_expr((self.package, *mid).into()).span;
945 let (_, is_unique) =
946 is_updatable_in_place(env, globals.get_expr((self.package, *lhs).into()));
947 if is_unique {
948 self.eval_update_index_in_place(env, globals, *lhs, mid_span)?;
949 return Ok(());
950 }
951 self.push_val();
952 self.eval_expr(env, sim, globals, out, *lhs)?;
953 self.eval_update_index(mid_span)?;
954 self.eval_assign(env, globals, *lhs)?;
955 }
956 ExprKind::BinOp(op, _, rhs) => {
957 let rhs_span = globals.get_expr((self.package, *rhs).into()).span;
958 self.eval_binop(*op, rhs_span)?;
959 }
960 ExprKind::Block(..) => panic!("block expr should be handled by control flow"),
961 ExprKind::Call(callee_expr, args_expr) => {
962 let callable_span = globals.get_expr((self.package, *callee_expr).into()).span;
963 let args_span = globals.get_expr((self.package, *args_expr).into()).span;
964 self.eval_call(env, sim, globals, callable_span, args_span, out)?;
965 }
966 ExprKind::Closure(args, callable) => {
967 let closure = resolve_closure(env, self.package, expr.span, args, *callable)?;
968 self.set_val_register(closure);
969 }
970 ExprKind::Fail(..) => {
971 return Err(Error::UserFail(
972 self.take_val_register().unwrap_string().to_string(),
973 self.to_global_span(expr.span),
974 ));
975 }
976 ExprKind::Field(_, field) => self.eval_field(field.clone()),
977 ExprKind::Hole => panic!("hole expr should be disallowed by passes"),
978 ExprKind::If(..) => {
979 panic!("if expr should be handled by control flow")
980 }
981 ExprKind::Index(_, rhs) => {
982 let rhs_span = globals.get_expr((self.package, *rhs).into()).span;
983 self.eval_index(rhs_span)?;
984 }
985 ExprKind::Lit(lit) => {
986 self.set_val_register(lit_to_val(lit));
987 }
988 ExprKind::Range(start, step, end) => {
989 self.eval_range(start.is_some(), step.is_some(), end.is_some());
990 }
991 ExprKind::Return(..) => panic!("return expr should be handled by control flow"),
992 ExprKind::Struct(_, copy, fields) => self.eval_struct(*copy, fields),
993 ExprKind::String(components) => self.collect_string(components),
994 ExprKind::UpdateIndex(_, mid, _) => {
995 let mid_span = globals.get_expr((self.package, *mid).into()).span;
996 self.eval_update_index(mid_span)?;
997 }
998 ExprKind::Tuple(tup) => self.eval_tup(tup.len()),
999 ExprKind::UnOp(op, _) => self.eval_unop(*op),
1000 ExprKind::UpdateField(_, field, _) => {
1001 self.eval_update_field(field.clone());
1002 }
1003 ExprKind::Var(res, _) => {
1004 self.set_val_register(resolve_binding(env, self.package, *res, expr.span)?);
1005 }
1006 ExprKind::While(..) => {
1007 panic!("while expr should be handled by control flow")
1008 }
1009 }
1010
1011 Ok(())
1012 }
1013
1014 fn collect_string(&mut self, components: &[StringComponent]) {
1015 if let [StringComponent::Lit(str)] = components {
1016 self.set_val_register(Value::String(Rc::clone(str)));
1017 return;
1018 }
1019
1020 let mut string = String::new();
1021 for component in components.iter().rev() {
1022 match component {
1023 StringComponent::Expr(..) => {
1024 let expr_str = format!("{}", self.pop_val());
1025 string.insert_str(0, &expr_str);
1026 }
1027 StringComponent::Lit(lit) => {
1028 string.insert_str(0, lit);
1029 }
1030 }
1031 }
1032 self.set_val_register(Value::String(Rc::from(string)));
1033 }
1034
1035 fn eval_arr(&mut self, len: usize) {
1036 let arr = self.pop_vals(len);
1037 self.set_val_register(Value::Array(arr.into()));
1038 }
1039
1040 fn eval_arr_lit(&mut self, arr: &Vec<ExprId>, globals: &impl PackageStoreLookup) {
1041 let mut new_arr: Rc<Vec<Value>> = Rc::new(Vec::with_capacity(arr.len()));
1042 for id in arr {
1043 let ExprKind::Lit(lit) = &globals.get_expr((self.package, *id).into()).kind else {
1044 panic!("expr kind should be lit")
1045 };
1046 Rc::get_mut(&mut new_arr)
1047 .expect("array should be uniquely referenced")
1048 .push(lit_to_val(lit));
1049 }
1050 self.set_val_register(Value::Array(new_arr));
1051 }
1052
1053 fn eval_array_append_in_place(
1054 &mut self,
1055 env: &mut Env,
1056 globals: &impl PackageStoreLookup,
1057 lhs: ExprId,
1058 ) -> Result<(), Error> {
1059 let lhs = globals.get_expr((self.package, lhs).into());
1060 let rhs = self.take_val_register();
1061 match (&lhs.kind, rhs) {
1062 (&ExprKind::Var(Res::Local(id), _), rhs) => match env.get_mut(id) {
1063 Some(var) => {
1064 var.value.append_array(rhs);
1065 }
1066 None => return Err(Error::UnboundName(self.to_global_span(lhs.span))),
1067 },
1068 _ => unreachable!("unassignable array update pattern should be disallowed by compiler"),
1069 }
1070 Ok(())
1071 }
1072
1073 fn eval_arr_repeat(&mut self, span: Span) -> Result<(), Error> {
1074 let size_val = self.take_val_register().unwrap_int();
1075 let item_val = self.pop_val();
1076 let s = match size_val.try_into() {
1077 Ok(i) => Ok(i),
1078 Err(_) => Err(Error::InvalidArrayLength(
1079 size_val,
1080 self.to_global_span(span),
1081 )),
1082 }?;
1083 self.set_val_register(Value::Array(vec![item_val; s].into()));
1084 Ok(())
1085 }
1086
1087 fn eval_assign(
1088 &mut self,
1089 env: &mut Env,
1090 globals: &impl PackageStoreLookup,
1091 lhs: ExprId,
1092 ) -> Result<(), Error> {
1093 let rhs = self.take_val_register();
1094 self.update_binding(env, globals, lhs, rhs)
1095 }
1096
1097 fn eval_bind(&mut self, env: &mut Env, globals: &impl PackageStoreLookup, pat: PatId) {
1098 let val = self.take_val_register();
1099 self.bind_value(env, globals, pat, val);
1100 }
1101
1102 fn eval_binop(&mut self, op: BinOp, span: Span) -> Result<(), Error> {
1103 match op {
1104 BinOp::Add => self.eval_binop_simple(eval_binop_add),
1105 BinOp::AndB => self.eval_binop_simple(eval_binop_andb),
1106 BinOp::Div => self.eval_binop_with_error(span, eval_binop_div)?,
1107 BinOp::Eq => self.eval_binop_with_error(span, eval_binop_eq)?,
1108 BinOp::Exp => self.eval_binop_with_error(span, eval_binop_exp)?,
1109 BinOp::Gt => self.eval_binop_simple(eval_binop_gt),
1110 BinOp::Gte => self.eval_binop_simple(eval_binop_gte),
1111 BinOp::Lt => self.eval_binop_simple(eval_binop_lt),
1112 BinOp::Lte => self.eval_binop_simple(eval_binop_lte),
1113 BinOp::Mod => self.eval_binop_with_error(span, eval_binop_mod)?,
1114 BinOp::Mul => self.eval_binop_simple(eval_binop_mul),
1115 BinOp::Neq => self.eval_binop_with_error(span, eval_binop_neq)?,
1116 BinOp::OrB => self.eval_binop_simple(eval_binop_orb),
1117 BinOp::Shl => self.eval_binop_with_error(span, eval_binop_shl)?,
1118 BinOp::Shr => self.eval_binop_with_error(span, eval_binop_shr)?,
1119 BinOp::Sub => self.eval_binop_simple(eval_binop_sub),
1120 BinOp::XorB => self.eval_binop_simple(eval_binop_xorb),
1121
1122 // Logical operators should be handled by control flow
1123 BinOp::AndL | BinOp::OrL => {}
1124 }
1125 Ok(())
1126 }
1127
1128 fn eval_binop_simple(&mut self, binop_func: impl FnOnce(Value, Value) -> Value) {
1129 let rhs_val = self.take_val_register();
1130 let lhs_val = self.pop_val();
1131 self.set_val_register(binop_func(lhs_val, rhs_val));
1132 }
1133
1134 fn eval_binop_with_error(
1135 &mut self,
1136 span: Span,
1137 binop_func: impl FnOnce(Value, Value, PackageSpan) -> Result<Value, Error>,
1138 ) -> Result<(), Error> {
1139 let span = self.to_global_span(span);
1140 let rhs_val = self.take_val_register();
1141 let lhs_val = self.pop_val();
1142 self.set_val_register(binop_func(lhs_val, rhs_val, span)?);
1143 Ok(())
1144 }
1145
1146 fn eval_call(
1147 &mut self,
1148 env: &mut Env,
1149 sim: &mut impl Backend<ResultType = impl Into<val::Result>>,
1150 globals: &impl PackageStoreLookup,
1151 callable_span: Span,
1152 arg_span: Span,
1153 out: &mut impl Receiver,
1154 ) -> Result<(), Error> {
1155 let arg = self.take_val_register();
1156 let (callee_id, functor, fixed_args) = match self.pop_val() {
1157 Value::Closure(inner) => (inner.id, inner.functor, Some(inner.fixed_args)),
1158 Value::Global(id, functor) => (id, functor, None),
1159 _ => panic!("value is not callable"),
1160 };
1161
1162 let arg_span = self.to_global_span(arg_span);
1163
1164 let callee = match globals.get_global(callee_id) {
1165 Some(Global::Callable(callable)) => callable,
1166 Some(Global::Udt) => {
1167 self.set_val_register(arg);
1168 return Ok(());
1169 }
1170 None => return Err(Error::UnboundName(self.to_global_span(callable_span))),
1171 };
1172
1173 let callee_span = self.to_global_span(callee.span);
1174
1175 let spec = spec_from_functor_app(functor);
1176 match &callee.implementation {
1177 CallableImpl::Intrinsic if is_counting_call(&callee.name.name) => {
1178 self.push_frame(Vec::new().into(), callee_id, functor);
1179
1180 let val = self.counting_call(&callee.name.name, arg, arg_span)?;
1181
1182 self.set_val_register(val);
1183 self.leave_frame();
1184 Ok(())
1185 }
1186 CallableImpl::Intrinsic => self.eval_intrinsic(
1187 env,
1188 callee_id,
1189 functor,
1190 callee,
1191 sim,
1192 callee_span,
1193 arg,
1194 arg_span,
1195 out,
1196 ),
1197 CallableImpl::Spec(specialized_implementation) => {
1198 let spec_decl = match spec {
1199 Spec::Body => Some(&specialized_implementation.body),
1200 Spec::Adj => specialized_implementation.adj.as_ref(),
1201 Spec::Ctl => specialized_implementation.ctl.as_ref(),
1202 Spec::CtlAdj => specialized_implementation.ctl_adj.as_ref(),
1203 }
1204 .expect("missing specialization should be a compilation error");
1205 self.push_frame(spec_decl.exec_graph.clone(), callee_id, functor);
1206 self.push_scope(env);
1207 self.increment_call_count(callee_id, functor);
1208
1209 self.bind_args_for_spec(
1210 env,
1211 globals,
1212 callee.input,
1213 spec_decl.input,
1214 arg,
1215 arg_span,
1216 functor.controlled,
1217 fixed_args,
1218 )?;
1219 Ok(())
1220 }
1221 CallableImpl::SimulatableIntrinsic(spec_decl) => {
1222 self.push_frame(spec_decl.exec_graph.clone(), callee_id, functor);
1223 self.push_scope(env);
1224
1225 self.bind_args_for_spec(
1226 env,
1227 globals,
1228 callee.input,
1229 spec_decl.input,
1230 arg,
1231 arg_span,
1232 functor.controlled,
1233 fixed_args,
1234 )?;
1235 Ok(())
1236 }
1237 }
1238 }
1239
1240 #[allow(clippy::too_many_arguments)]
1241 fn eval_intrinsic(
1242 &mut self,
1243 env: &mut Env,
1244 callee_id: StoreItemId,
1245 functor: FunctorApp,
1246 callee: &fir::CallableDecl,
1247 sim: &mut impl Backend<ResultType = impl Into<val::Result>>,
1248 callee_span: PackageSpan,
1249 arg: Value,
1250 arg_span: PackageSpan,
1251 out: &mut impl Receiver,
1252 ) -> Result<(), Error> {
1253 self.push_frame(Vec::new().into(), callee_id, functor);
1254 self.current_span = callee_span.span;
1255 self.increment_call_count(callee_id, functor);
1256 let name = &callee.name.name;
1257 let val = match name.as_ref() {
1258 "__quantum__rt__qubit_allocate" => {
1259 let q = Rc::new(Qubit(sim.qubit_allocate()));
1260 env.track_qubit(Rc::clone(&q));
1261 if let Some(counter) = &mut self.qubit_counter {
1262 counter.allocated(q.0);
1263 }
1264 Value::Qubit(q.into())
1265 }
1266 "__quantum__rt__qubit_release" => {
1267 let qubit = arg
1268 .unwrap_qubit()
1269 .try_deref()
1270 .ok_or(Error::QubitDoubleRelease(arg_span))?;
1271 env.release_qubit(&qubit);
1272 if sim.qubit_release(qubit.0) {
1273 Value::unit()
1274 } else {
1275 return Err(Error::ReleasedQubitNotZero(qubit.0, arg_span));
1276 }
1277 }
1278 _ => {
1279 let val = intrinsic::call(
1280 name,
1281 callee_span,
1282 arg,
1283 arg_span,
1284 sim,
1285 &mut self.rng.borrow_mut(),
1286 out,
1287 )?;
1288 if val == Value::unit() && callee.output != Ty::UNIT {
1289 return Err(Error::UnsupportedIntrinsicType(
1290 callee.name.name.to_string(),
1291 callee_span,
1292 ));
1293 }
1294 val
1295 }
1296 };
1297 self.set_val_register(val);
1298 self.leave_frame();
1299 Ok(())
1300 }
1301
1302 fn eval_field(&mut self, field: Field) {
1303 let record = self.take_val_register();
1304 let val = match (record, field) {
1305 (Value::Range(inner), Field::Prim(PrimField::Start)) => Value::Int(
1306 inner
1307 .start
1308 .expect("range access should be validated by compiler"),
1309 ),
1310 (Value::Range(inner), Field::Prim(PrimField::Step)) => Value::Int(inner.step),
1311 (Value::Range(inner), Field::Prim(PrimField::End)) => Value::Int(
1312 inner
1313 .end
1314 .expect("range access should be validated by compiler"),
1315 ),
1316 (record, Field::Path(path)) => {
1317 follow_field_path(record, &path.indices).expect("field path should be valid")
1318 }
1319 (ref value, ref field) => {
1320 panic!("invalid field access. value: {value:?}, field: {field:?}")
1321 }
1322 };
1323 self.set_val_register(val);
1324 }
1325
1326 fn eval_index(&mut self, span: Span) -> Result<(), Error> {
1327 let index_val = self.take_val_register();
1328 let arr = self.pop_val().unwrap_array();
1329 match &index_val {
1330 Value::Int(i) => {
1331 self.set_val_register(index_array(&arr, *i, self.to_global_span(span))?);
1332 }
1333 Value::Range(inner) => {
1334 self.set_val_register(slice_array(
1335 &arr,
1336 inner.start,
1337 inner.step,
1338 inner.end,
1339 self.to_global_span(span),
1340 )?);
1341 }
1342 _ => panic!("array should only be indexed by Int or Range"),
1343 }
1344 Ok(())
1345 }
1346
1347 fn eval_range(&mut self, has_start: bool, has_step: bool, has_end: bool) {
1348 let end = if has_end {
1349 Some(self.take_val_register().unwrap_int())
1350 } else {
1351 None
1352 };
1353 let step = if has_step {
1354 self.pop_val().unwrap_int()
1355 } else {
1356 val::DEFAULT_RANGE_STEP
1357 };
1358 let start = if has_start {
1359 Some(self.pop_val().unwrap_int())
1360 } else {
1361 None
1362 };
1363 self.set_val_register(Value::Range(val::Range { start, step, end }.into()));
1364 }
1365
1366 fn eval_struct(&mut self, copy: Option<ExprId>, fields: &[FieldAssign]) {
1367 // Extract a flat list of field indexes.
1368 let field_indexes = fields
1369 .iter()
1370 .map(|f| match &f.field {
1371 Field::Path(path) => match path.indices.as_slice() {
1372 &[i] => i,
1373 _ => panic!("field path for struct should have a single index"),
1374 },
1375 _ => panic!("invalid field for struct"),
1376 })
1377 .collect::<Vec<_>>();
1378
1379 let len = fields.len();
1380
1381 let (field_vals, mut strct) = if copy.is_some() {
1382 // Get the field values and the copy struct value.
1383 let field_vals = self.pop_vals(len + 1);
1384 let (copy, field_vals) = field_vals.split_first().expect("copy value is expected");
1385
1386 // Make a clone of the copy struct value.
1387 (field_vals.to_vec(), copy.clone().unwrap_tuple().to_vec())
1388 } else {
1389 // Make an empty struct of the appropriate size.
1390 (self.pop_vals(len), vec![Value::Int(0); len])
1391 };
1392
1393 // Insert the field values into the new struct.
1394 assert!(
1395 field_vals.len() == field_indexes.len(),
1396 "number of given field values should match the number of given struct fields"
1397 );
1398 for (i, val) in field_indexes.iter().zip(field_vals.into_iter()) {
1399 strct[*i] = val;
1400 }
1401
1402 self.set_val_register(Value::Tuple(strct.into()));
1403 }
1404
1405 fn eval_update_index(&mut self, span: Span) -> Result<(), Error> {
1406 let values = self.take_val_register().unwrap_array();
1407 let update = self.pop_val();
1408 let index = self.pop_val();
1409 let span = self.to_global_span(span);
1410 match index {
1411 Value::Int(index) => self.eval_update_index_single(&values, index, update, span),
1412 Value::Range(inner) => self.eval_update_index_range(
1413 &values,
1414 inner.start,
1415 inner.step,
1416 inner.end,
1417 update,
1418 span,
1419 ),
1420 _ => unreachable!("array should only be indexed by Int or Range"),
1421 }
1422 }
1423
1424 fn eval_update_index_single(
1425 &mut self,
1426 values: &[Value],
1427 index: i64,
1428 update: Value,
1429 span: PackageSpan,
1430 ) -> Result<(), Error> {
1431 let updated_array = update_index_single(values, index, update, span)?;
1432 self.set_val_register(updated_array);
1433 Ok(())
1434 }
1435
1436 fn eval_update_index_range(
1437 &mut self,
1438 values: &[Value],
1439 start: Option<i64>,
1440 step: i64,
1441 end: Option<i64>,
1442 update: Value,
1443 span: PackageSpan,
1444 ) -> Result<(), Error> {
1445 let updated_array = update_index_range(values, start, step, end, update, span)?;
1446 self.set_val_register(updated_array);
1447 Ok(())
1448 }
1449
1450 fn eval_update_index_in_place(
1451 &mut self,
1452 env: &mut Env,
1453 globals: &impl PackageStoreLookup,
1454 lhs: ExprId,
1455 span: Span,
1456 ) -> Result<(), Error> {
1457 let update = self.take_val_register();
1458 let index = self.pop_val();
1459 let span = self.to_global_span(span);
1460 match index {
1461 Value::Int(index) => {
1462 if index < 0 {
1463 return Err(Error::InvalidNegativeInt(index, span));
1464 }
1465 self.update_array_index_single(env, globals, lhs, span, index, update)
1466 }
1467 range @ Value::Range(..) => {
1468 self.update_array_index_range(env, globals, lhs, span, &range, update)
1469 }
1470 _ => unreachable!("array should only be indexed by Int or Range"),
1471 }
1472 }
1473
1474 fn eval_tup(&mut self, len: usize) {
1475 let tup = self.pop_vals(len);
1476 self.set_val_register(Value::Tuple(tup.into()));
1477 }
1478
1479 fn eval_unop(&mut self, op: UnOp) {
1480 let val = self.take_val_register();
1481 match op {
1482 UnOp::Functor(functor) => match val {
1483 Value::Closure(inner) => {
1484 self.set_val_register(Value::Closure(
1485 val::Closure {
1486 functor: update_functor_app(functor, inner.functor),
1487 ..*inner
1488 }
1489 .into(),
1490 ));
1491 }
1492 Value::Global(id, app) => {
1493 self.set_val_register(Value::Global(id, update_functor_app(functor, app)));
1494 }
1495 _ => panic!("value should be callable"),
1496 },
1497 UnOp::Neg => match val {
1498 Value::BigInt(v) => self.set_val_register(Value::BigInt(v.neg())),
1499 Value::Double(v) => self.set_val_register(Value::Double(v.neg())),
1500 Value::Int(v) => self.set_val_register(Value::Int(v.wrapping_neg())),
1501 _ => panic!("value should be number"),
1502 },
1503 UnOp::NotB => match val {
1504 Value::Int(v) => self.set_val_register(Value::Int(!v)),
1505 Value::BigInt(v) => self.set_val_register(Value::BigInt(!v)),
1506 _ => panic!("value should be Int or BigInt"),
1507 },
1508 UnOp::NotL => match val {
1509 Value::Bool(b) => self.set_val_register(Value::Bool(!b)),
1510 _ => panic!("value should be bool"),
1511 },
1512 UnOp::Pos => match val {
1513 Value::BigInt(_) | Value::Int(_) | Value::Double(_) => self.set_val_register(val),
1514 _ => panic!("value should be number"),
1515 },
1516 UnOp::Unwrap => self.set_val_register(val),
1517 }
1518 }
1519
1520 fn eval_update_field(&mut self, field: Field) {
1521 let record = self.take_val_register();
1522 let value = self.pop_val();
1523 let update = match (record, field) {
1524 (Value::Range(mut inner), Field::Prim(PrimField::Start)) => {
1525 inner.start = Some(value.unwrap_int());
1526 Value::Range(inner)
1527 }
1528 (Value::Range(mut inner), Field::Prim(PrimField::Step)) => {
1529 inner.step = value.unwrap_int();
1530 Value::Range(inner)
1531 }
1532 (Value::Range(mut inner), Field::Prim(PrimField::End)) => {
1533 inner.end = Some(value.unwrap_int());
1534 Value::Range(inner)
1535 }
1536 (record, Field::Path(path)) => update_field_path(&record, &path.indices, &value)
1537 .expect("field path should be valid"),
1538 _ => panic!("invalid field access"),
1539 };
1540 self.set_val_register(update);
1541 }
1542
1543 fn bind_value(&self, env: &mut Env, globals: &impl PackageStoreLookup, pat: PatId, val: Value) {
1544 let pat = globals.get_pat((self.package, pat).into());
1545 match &pat.kind {
1546 PatKind::Bind(variable) => {
1547 let scope = env.scopes.last_mut().expect("binding should have a scope");
1548 scope.bindings.insert(
1549 variable.id,
1550 Variable {
1551 name: variable.name.clone(),
1552 value: val,
1553 span: variable.span,
1554 },
1555 );
1556 }
1557 PatKind::Discard => {}
1558 PatKind::Tuple(tup) => {
1559 let val_tup = val.unwrap_tuple();
1560 for (pat, val) in tup.iter().zip(val_tup.iter()) {
1561 self.bind_value(env, globals, *pat, val.clone());
1562 }
1563 }
1564 }
1565 }
1566
1567 #[allow(clippy::similar_names)]
1568 fn update_binding(
1569 &self,
1570 env: &mut Env,
1571 globals: &impl PackageStoreLookup,
1572 lhs: ExprId,
1573 rhs: Value,
1574 ) -> Result<(), Error> {
1575 let lhs = globals.get_expr((self.package, lhs).into());
1576 match (&lhs.kind, rhs) {
1577 (ExprKind::Hole, _) => {}
1578 (&ExprKind::Var(Res::Local(id), _), rhs) => match env.get_mut(id) {
1579 Some(var) => {
1580 var.value = rhs;
1581 }
1582 None => return Err(Error::UnboundName(self.to_global_span(lhs.span))),
1583 },
1584 (ExprKind::Tuple(var_tup), Value::Tuple(tup)) => {
1585 for (expr, val) in var_tup.iter().zip(tup.iter()) {
1586 self.update_binding(env, globals, *expr, val.clone())?;
1587 }
1588 }
1589 _ => unreachable!("unassignable pattern should be disallowed by compiler"),
1590 }
1591 Ok(())
1592 }
1593
1594 fn update_array_index_single(
1595 &mut self,
1596 env: &mut Env,
1597 globals: &impl PackageStoreLookup,
1598 lhs: ExprId,
1599 span: PackageSpan,
1600 index: i64,
1601 rhs: Value,
1602 ) -> Result<(), Error> {
1603 let lhs = globals.get_expr((self.package, lhs).into());
1604 match &lhs.kind {
1605 &ExprKind::Var(Res::Local(id), _) => match env.get_mut(id) {
1606 Some(var) => {
1607 var.value.update_array(index, rhs, span)?;
1608 }
1609 None => return Err(Error::UnboundName(self.to_global_span(lhs.span))),
1610 },
1611 _ => unreachable!("unassignable array update pattern should be disallowed by compiler"),
1612 }
1613 Ok(())
1614 }
1615
1616 #[allow(clippy::similar_names)] // `env` and `end` are similar but distinct
1617 fn update_array_index_range(
1618 &mut self,
1619 env: &mut Env,
1620 globals: &impl PackageStoreLookup,
1621 lhs: ExprId,
1622 range_span: PackageSpan,
1623 range: &Value,
1624 update: Value,
1625 ) -> Result<(), Error> {
1626 let lhs = globals.get_expr((self.package, lhs).into());
1627 match &lhs.kind {
1628 &ExprKind::Var(Res::Local(id), _) => match env.get_mut(id) {
1629 Some(var) => {
1630 let rhs = update.unwrap_array();
1631 let Value::Array(arr) = &mut var.value else {
1632 panic!("variable should be an array");
1633 };
1634 let Value::Range(inner) = range else {
1635 unreachable!("range should be a Value::Range");
1636 };
1637 let range = make_range(arr, inner.start, inner.step, inner.end, range_span)?;
1638 for (idx, rhs) in range.into_iter().zip(rhs.iter()) {
1639 if idx < 0 {
1640 return Err(Error::InvalidNegativeInt(idx, range_span));
1641 }
1642 var.value.update_array(idx, rhs.clone(), range_span)?;
1643 }
1644 }
1645 None => return Err(Error::UnboundName(self.to_global_span(lhs.span))),
1646 },
1647 _ => unreachable!("unassignable array update pattern should be disallowed by compiler"),
1648 }
1649 Ok(())
1650 }
1651
1652 #[allow(clippy::too_many_arguments)]
1653 fn bind_args_for_spec(
1654 &self,
1655 env: &mut Env,
1656 globals: &impl PackageStoreLookup,
1657 decl_pat: PatId,
1658 spec_pat: Option<PatId>,
1659 args_val: Value,
1660 args_span: PackageSpan,
1661 ctl_count: u8,
1662 fixed_args: Option<Rc<[Value]>>,
1663 ) -> Result<(), Error> {
1664 match spec_pat {
1665 Some(spec_pat) => {
1666 assert!(
1667 ctl_count > 0,
1668 "spec pattern tuple used without controlled functor"
1669 );
1670
1671 let mut tup = args_val;
1672 let mut ctls = vec![];
1673 for _ in 0..ctl_count {
1674 let [c, rest] = &*tup.unwrap_tuple() else {
1675 panic!("tuple should be arity 2");
1676 };
1677 ctls.extend_from_slice(&c.clone().unwrap_array());
1678 tup = rest.clone();
1679 }
1680
1681 if !are_ctls_unique(&ctls, &tup) {
1682 return Err(Error::QubitUniqueness(args_span));
1683 }
1684
1685 self.bind_value(env, globals, spec_pat, Value::Array(ctls.into()));
1686 self.bind_value(env, globals, decl_pat, merge_fixed_args(fixed_args, tup));
1687 }
1688 None => self.bind_value(
1689 env,
1690 globals,
1691 decl_pat,
1692 merge_fixed_args(fixed_args, args_val),
1693 ),
1694 }
1695 Ok(())
1696 }
1697
1698 fn to_global_span(&self, span: Span) -> PackageSpan {
1699 PackageSpan {
1700 package: map_fir_package_to_hir(self.package),
1701 span,
1702 }
1703 }
1704
1705 fn counting_call(&mut self, name: &str, arg: Value, span: PackageSpan) -> Result<Value, Error> {
1706 let counting_key = |arg: Value| match arg {
1707 Value::Closure(closure) => make_counting_key(closure.id, closure.functor),
1708 Value::Global(id, functor) => make_counting_key(id, functor),
1709 _ => panic!("value should be callable"),
1710 };
1711 match name {
1712 "StartCountingOperation" | "StartCountingFunction" => {
1713 if self.call_counts.insert(counting_key(arg), 0).is_some() {
1714 Err(Error::CallableAlreadyCounted(span))
1715 } else {
1716 Ok(Value::unit())
1717 }
1718 }
1719 "StopCountingOperation" | "StopCountingFunction" => {
1720 if let Some(count) = self.call_counts.remove(&counting_key(arg)) {
1721 Ok(Value::Int(count))
1722 } else {
1723 Err(Error::CallableNotCounted(span))
1724 }
1725 }
1726 "StartCountingQubits" => {
1727 if self
1728 .qubit_counter
1729 .replace(QubitCounter::default())
1730 .is_some()
1731 {
1732 Err(Error::QubitsAlreadyCounted(span))
1733 } else {
1734 Ok(Value::unit())
1735 }
1736 }
1737 "StopCountingQubits" => {
1738 if let Some(qubit_counter) = self.qubit_counter.take() {
1739 Ok(Value::Int(qubit_counter.into_count()))
1740 } else {
1741 Err(Error::QubitsNotCounted(span))
1742 }
1743 }
1744 _ => panic!("unknown counting call"),
1745 }
1746 }
1747
1748 fn increment_call_count(&mut self, callee_id: StoreItemId, functor: FunctorApp) {
1749 if let Some(count) = self
1750 .call_counts
1751 .get_mut(&make_counting_key(callee_id, functor))
1752 {
1753 *count += 1;
1754 }
1755 }
1756}
1757
1758pub fn are_ctls_unique(ctls: &[Value], tup: &Value) -> bool {
1759 let mut qubits = FxHashSet::default();
1760 for ctl in ctls.iter().flat_map(Value::qubits) {
1761 if let Some(ctl) = ctl.try_deref() {
1762 if !qubits.insert(ctl) {
1763 return false;
1764 }
1765 }
1766 }
1767 for qubit in tup.qubits() {
1768 if let Some(qubit) = qubit.try_deref() {
1769 if qubits.contains(&qubit) {
1770 return false;
1771 }
1772 }
1773 }
1774 true
1775}
1776
1777fn merge_fixed_args(fixed_args: Option<Rc<[Value]>>, arg: Value) -> Value {
1778 if let Some(fixed_args) = fixed_args {
1779 Value::Tuple(fixed_args.iter().cloned().chain(iter::once(arg)).collect())
1780 } else {
1781 arg
1782 }
1783}
1784
1785fn resolve_binding(env: &Env, package: PackageId, res: Res, span: Span) -> Result<Value, Error> {
1786 Ok(match res {
1787 Res::Err => panic!("resolution error"),
1788 Res::Item(item) => Value::Global(
1789 StoreItemId {
1790 package: item.package.unwrap_or(package),
1791 item: item.item,
1792 },
1793 FunctorApp::default(),
1794 ),
1795 Res::Local(id) => env
1796 .get(id)
1797 .ok_or(Error::UnboundName(PackageSpan {
1798 package: map_fir_package_to_hir(package),
1799 span,
1800 }))?
1801 .value
1802 .clone(),
1803 })
1804}
1805
1806fn spec_from_functor_app(functor: FunctorApp) -> Spec {
1807 match (functor.adjoint, functor.controlled) {
1808 (false, 0) => Spec::Body,
1809 (true, 0) => Spec::Adj,
1810 (false, _) => Spec::Ctl,
1811 (true, _) => Spec::CtlAdj,
1812 }
1813}
1814
1815pub fn resolve_closure(
1816 env: &Env,
1817 package: PackageId,
1818 span: Span,
1819 args: &[LocalVarId],
1820 callable: LocalItemId,
1821) -> Result<Value, Error> {
1822 let args: Option<_> = args
1823 .iter()
1824 .map(|&arg| Some(env.get(arg)?.value.clone()))
1825 .collect();
1826 let args: Vec<_> = args.ok_or(Error::UnboundName(PackageSpan {
1827 package: map_fir_package_to_hir(package),
1828 span,
1829 }))?;
1830 let callable = StoreItemId {
1831 package,
1832 item: callable,
1833 };
1834 Ok(Value::Closure(
1835 val::Closure {
1836 fixed_args: args.into(),
1837 id: callable,
1838 functor: FunctorApp::default(),
1839 }
1840 .into(),
1841 ))
1842}
1843
1844fn lit_to_val(lit: &Lit) -> Value {
1845 match lit {
1846 Lit::BigInt(v) => Value::BigInt(v.clone()),
1847 Lit::Bool(v) => Value::Bool(*v),
1848 Lit::Double(v) => Value::Double(*v),
1849 Lit::Int(v) => Value::Int(*v),
1850 Lit::Pauli(v) => Value::Pauli(*v),
1851 Lit::Result(fir::Result::Zero) => Value::RESULT_ZERO,
1852 Lit::Result(fir::Result::One) => Value::RESULT_ONE,
1853 }
1854}
1855
1856fn eval_binop_eq(lhs_val: Value, rhs_val: Value, rhs_span: PackageSpan) -> Result<Value, Error> {
1857 match (lhs_val, rhs_val) {
1858 (Value::Result(val::Result::Id(_)), _) | (_, Value::Result(val::Result::Id(_))) => {
1859 // Comparison of result ids is nonsensical, so we prevent it.
1860 // This code path is reachable when using the circuit builder backend
1861 // since we don't currently do runtime capability analysis
1862 // to prevent executing programs that do result comparisons.
1863 Err(Error::ResultComparisonUnsupported(rhs_span))
1864 }
1865 (Value::Result(val::Result::Loss), _) | (_, Value::Result(val::Result::Loss)) => {
1866 // Loss is not comparable and should be checked ahead of time, so treat this as a runtime
1867 // failure.
1868 Err(Error::ResultLossComparisonUnsupported(rhs_span))
1869 }
1870 (lhs, rhs) => Ok(Value::Bool(lhs == rhs)),
1871 }
1872}
1873
1874fn eval_binop_neq(lhs_val: Value, rhs_val: Value, rhs_span: PackageSpan) -> Result<Value, Error> {
1875 match (lhs_val, rhs_val) {
1876 (Value::Result(val::Result::Id(_)), _) | (_, Value::Result(val::Result::Id(_))) => {
1877 // Comparison of result ids is nonsensical, so we prevent it.
1878 // This code path is reachable when using the circuit builder backend
1879 // since we don't currently do runtime capability analysis
1880 // to prevent executing programs that do result comparisons.
1881 Err(Error::ResultComparisonUnsupported(rhs_span))
1882 }
1883 (Value::Result(val::Result::Loss), _) | (_, Value::Result(val::Result::Loss)) => {
1884 // Loss is not comparable and should be checked ahead of time, so treat this as a runtime
1885 // failure.
1886 Err(Error::ResultLossComparisonUnsupported(rhs_span))
1887 }
1888 (lhs, rhs) => Ok(Value::Bool(lhs != rhs)),
1889 }
1890}
1891
1892fn eval_binop_add(lhs_val: Value, rhs_val: Value) -> Value {
1893 match lhs_val {
1894 Value::Array(arr) => {
1895 let rhs_arr = rhs_val.unwrap_array();
1896 let items: Vec<_> = arr.iter().cloned().chain(rhs_arr.iter().cloned()).collect();
1897 Value::Array(items.into())
1898 }
1899 Value::BigInt(val) => {
1900 let rhs = rhs_val.unwrap_big_int();
1901 Value::BigInt(val + rhs)
1902 }
1903 Value::Double(val) => {
1904 let rhs = rhs_val.unwrap_double();
1905 Value::Double(val + rhs)
1906 }
1907 Value::Int(val) => {
1908 let rhs = rhs_val.unwrap_int();
1909 Value::Int(val.wrapping_add(rhs))
1910 }
1911 Value::String(val) => {
1912 let rhs = rhs_val.unwrap_string();
1913 Value::String((val.to_string() + &rhs).into())
1914 }
1915 _ => panic!("value is not addable: {}", lhs_val.type_name()),
1916 }
1917}
1918
1919fn eval_binop_andb(lhs_val: Value, rhs_val: Value) -> Value {
1920 match lhs_val {
1921 Value::BigInt(val) => {
1922 let rhs = rhs_val.unwrap_big_int();
1923 Value::BigInt(val & rhs)
1924 }
1925 Value::Int(val) => {
1926 let rhs = rhs_val.unwrap_int();
1927 Value::Int(val & rhs)
1928 }
1929 _ => panic!("value type does not support andb"),
1930 }
1931}
1932
1933fn eval_binop_div(lhs_val: Value, rhs_val: Value, rhs_span: PackageSpan) -> Result<Value, Error> {
1934 match lhs_val {
1935 Value::BigInt(val) => {
1936 let rhs = rhs_val.unwrap_big_int();
1937 if rhs == BigInt::from(0) {
1938 Err(Error::DivZero(rhs_span))
1939 } else {
1940 Ok(Value::BigInt(val / rhs))
1941 }
1942 }
1943 Value::Int(val) => {
1944 let rhs = rhs_val.unwrap_int();
1945 if rhs == 0 {
1946 Err(Error::DivZero(rhs_span))
1947 } else {
1948 Ok(Value::Int(val.wrapping_div(rhs)))
1949 }
1950 }
1951 Value::Double(val) => {
1952 let rhs = rhs_val.unwrap_double();
1953 Ok(Value::Double(val / rhs))
1954 }
1955 _ => panic!("value should support div"),
1956 }
1957}
1958
1959fn eval_binop_exp(lhs_val: Value, rhs_val: Value, rhs_span: PackageSpan) -> Result<Value, Error> {
1960 match lhs_val {
1961 Value::BigInt(val) => {
1962 let rhs_val = rhs_val.unwrap_int();
1963 if rhs_val < 0 {
1964 Err(Error::InvalidNegativeInt(rhs_val, rhs_span))
1965 } else {
1966 let rhs_val: u32 = match rhs_val.try_into() {
1967 Ok(v) => Ok(v),
1968 Err(_) => Err(Error::IntTooLarge(rhs_val, rhs_span)),
1969 }?;
1970 Ok(Value::BigInt(val.pow(rhs_val)))
1971 }
1972 }
1973 Value::Double(val) => Ok(Value::Double(val.powf(rhs_val.unwrap_double()))),
1974 Value::Int(val) => {
1975 let rhs_val = rhs_val.unwrap_int();
1976 if rhs_val < 0 {
1977 Err(Error::InvalidNegativeInt(rhs_val, rhs_span))
1978 } else {
1979 let result: i64 = match rhs_val.try_into() {
1980 Ok(v) => val
1981 .checked_pow(v)
1982 .ok_or(Error::IntTooLarge(rhs_val, rhs_span)),
1983 Err(_) => Err(Error::IntTooLarge(rhs_val, rhs_span)),
1984 }?;
1985 Ok(Value::Int(result))
1986 }
1987 }
1988 _ => panic!("value should support exp"),
1989 }
1990}
1991
1992fn eval_binop_gt(lhs_val: Value, rhs_val: Value) -> Value {
1993 match lhs_val {
1994 Value::BigInt(val) => {
1995 let rhs = rhs_val.unwrap_big_int();
1996 Value::Bool(val > rhs)
1997 }
1998 Value::Int(val) => {
1999 let rhs = rhs_val.unwrap_int();
2000 Value::Bool(val > rhs)
2001 }
2002 Value::Double(val) => {
2003 let rhs = rhs_val.unwrap_double();
2004 Value::Bool(val > rhs)
2005 }
2006 _ => panic!("value doesn't support binop gt"),
2007 }
2008}
2009
2010fn eval_binop_gte(lhs_val: Value, rhs_val: Value) -> Value {
2011 match lhs_val {
2012 Value::BigInt(val) => {
2013 let rhs = rhs_val.unwrap_big_int();
2014 Value::Bool(val >= rhs)
2015 }
2016 Value::Int(val) => {
2017 let rhs = rhs_val.unwrap_int();
2018 Value::Bool(val >= rhs)
2019 }
2020 Value::Double(val) => {
2021 let rhs = rhs_val.unwrap_double();
2022 Value::Bool(val >= rhs)
2023 }
2024 _ => panic!("value doesn't support binop gte"),
2025 }
2026}
2027
2028fn eval_binop_lt(lhs_val: Value, rhs_val: Value) -> Value {
2029 match lhs_val {
2030 Value::BigInt(val) => {
2031 let rhs = rhs_val.unwrap_big_int();
2032 Value::Bool(val < rhs)
2033 }
2034 Value::Int(val) => {
2035 let rhs = rhs_val.unwrap_int();
2036 Value::Bool(val < rhs)
2037 }
2038 Value::Double(val) => {
2039 let rhs = rhs_val.unwrap_double();
2040 Value::Bool(val < rhs)
2041 }
2042 _ => panic!("value doesn't support binop lt"),
2043 }
2044}
2045
2046fn eval_binop_lte(lhs_val: Value, rhs_val: Value) -> Value {
2047 match lhs_val {
2048 Value::BigInt(val) => {
2049 let rhs = rhs_val.unwrap_big_int();
2050 Value::Bool(val <= rhs)
2051 }
2052 Value::Int(val) => {
2053 let rhs = rhs_val.unwrap_int();
2054 Value::Bool(val <= rhs)
2055 }
2056 Value::Double(val) => {
2057 let rhs = rhs_val.unwrap_double();
2058 Value::Bool(val <= rhs)
2059 }
2060 _ => panic!("value doesn't support binop lte"),
2061 }
2062}
2063
2064fn eval_binop_mod(lhs_val: Value, rhs_val: Value, rhs_span: PackageSpan) -> Result<Value, Error> {
2065 match lhs_val {
2066 Value::BigInt(val) => {
2067 let rhs = rhs_val.unwrap_big_int();
2068 if rhs == BigInt::from(0) {
2069 Err(Error::DivZero(rhs_span))
2070 } else {
2071 Ok(Value::BigInt(val % rhs))
2072 }
2073 }
2074 Value::Int(val) => {
2075 let rhs = rhs_val.unwrap_int();
2076 if rhs == 0 {
2077 Err(Error::DivZero(rhs_span))
2078 } else {
2079 Ok(Value::Int(val.wrapping_rem(rhs)))
2080 }
2081 }
2082 Value::Double(val) => {
2083 let rhs = rhs_val.unwrap_double();
2084 if rhs == 0.0 {
2085 Err(Error::DivZero(rhs_span))
2086 } else {
2087 Ok(Value::Double(val % rhs))
2088 }
2089 }
2090 _ => panic!("value should support mod"),
2091 }
2092}
2093
2094fn eval_binop_mul(lhs_val: Value, rhs_val: Value) -> Value {
2095 match lhs_val {
2096 Value::BigInt(val) => {
2097 let rhs = rhs_val.unwrap_big_int();
2098 Value::BigInt(val * rhs)
2099 }
2100 Value::Int(val) => {
2101 let rhs = rhs_val.unwrap_int();
2102 Value::Int(val.wrapping_mul(rhs))
2103 }
2104 Value::Double(val) => {
2105 let rhs = rhs_val.unwrap_double();
2106 Value::Double(val * rhs)
2107 }
2108 _ => panic!("value should support mul"),
2109 }
2110}
2111
2112fn eval_binop_orb(lhs_val: Value, rhs_val: Value) -> Value {
2113 match lhs_val {
2114 Value::BigInt(val) => {
2115 let rhs = rhs_val.unwrap_big_int();
2116 Value::BigInt(val | rhs)
2117 }
2118 Value::Int(val) => {
2119 let rhs = rhs_val.unwrap_int();
2120 Value::Int(val | rhs)
2121 }
2122 _ => panic!("value type does not support orb"),
2123 }
2124}
2125
2126fn eval_binop_shl(lhs_val: Value, rhs_val: Value, rhs_span: PackageSpan) -> Result<Value, Error> {
2127 Ok(match lhs_val {
2128 Value::BigInt(val) => {
2129 let rhs = rhs_val.unwrap_int();
2130 if rhs > 0 {
2131 Value::BigInt(val << rhs)
2132 } else {
2133 Value::BigInt(val >> rhs.abs())
2134 }
2135 }
2136 Value::Int(val) => {
2137 let rhs = rhs_val.unwrap_int();
2138 Value::Int(if rhs > 0 {
2139 let shift: u32 = rhs.try_into().or(Err(Error::IntTooLarge(rhs, rhs_span)))?;
2140 val.checked_shl(shift)
2141 .ok_or(Error::IntTooLarge(rhs, rhs_span))?
2142 } else {
2143 let shift: u32 = rhs
2144 .checked_neg()
2145 .ok_or(Error::IntTooLarge(rhs, rhs_span))?
2146 .try_into()
2147 .or(Err(Error::IntTooLarge(rhs, rhs_span)))?;
2148 val.checked_shr(shift)
2149 .ok_or(Error::IntTooLarge(rhs, rhs_span))?
2150 })
2151 }
2152 _ => panic!("value should support shl"),
2153 })
2154}
2155
2156fn eval_binop_shr(lhs_val: Value, rhs_val: Value, rhs_span: PackageSpan) -> Result<Value, Error> {
2157 Ok(match lhs_val {
2158 Value::BigInt(val) => {
2159 let rhs = rhs_val.unwrap_int();
2160 if rhs > 0 {
2161 Value::BigInt(val >> rhs)
2162 } else {
2163 Value::BigInt(val << rhs.abs())
2164 }
2165 }
2166 Value::Int(val) => {
2167 let rhs = rhs_val.unwrap_int();
2168 Value::Int(if rhs > 0 {
2169 let shift: u32 = rhs.try_into().or(Err(Error::IntTooLarge(rhs, rhs_span)))?;
2170 val.checked_shr(shift)
2171 .ok_or(Error::IntTooLarge(rhs, rhs_span))?
2172 } else {
2173 let shift: u32 = rhs
2174 .checked_neg()
2175 .ok_or(Error::IntTooLarge(rhs, rhs_span))?
2176 .try_into()
2177 .or(Err(Error::IntTooLarge(rhs, rhs_span)))?;
2178 val.checked_shl(shift)
2179 .ok_or(Error::IntTooLarge(rhs, rhs_span))?
2180 })
2181 }
2182 _ => panic!("value should support shr"),
2183 })
2184}
2185
2186fn eval_binop_sub(lhs_val: Value, rhs_val: Value) -> Value {
2187 match lhs_val {
2188 Value::BigInt(val) => {
2189 let rhs = rhs_val.unwrap_big_int();
2190 Value::BigInt(val - rhs)
2191 }
2192 Value::Double(val) => {
2193 let rhs = rhs_val.unwrap_double();
2194 Value::Double(val - rhs)
2195 }
2196 Value::Int(val) => {
2197 let rhs = rhs_val.unwrap_int();
2198 Value::Int(val.wrapping_sub(rhs))
2199 }
2200 _ => panic!("value is not subtractable"),
2201 }
2202}
2203
2204fn eval_binop_xorb(lhs_val: Value, rhs_val: Value) -> Value {
2205 match lhs_val {
2206 Value::BigInt(val) => {
2207 let rhs = rhs_val.unwrap_big_int();
2208 Value::BigInt(val ^ rhs)
2209 }
2210 Value::Int(val) => {
2211 let rhs = rhs_val.unwrap_int();
2212 Value::Int(val ^ rhs)
2213 }
2214 _ => panic!("value type does not support xorb"),
2215 }
2216}
2217
2218fn follow_field_path(mut value: Value, path: &[usize]) -> Option<Value> {
2219 for &index in path {
2220 let Value::Tuple(items) = value else {
2221 return None;
2222 };
2223 value = items[index].clone();
2224 }
2225 Some(value)
2226}
2227
2228fn update_field_path(record: &Value, path: &[usize], replace: &Value) -> Option<Value> {
2229 match (record, path) {
2230 (_, []) => Some(replace.clone()),
2231 (Value::Tuple(items), &[next_index, ..]) if next_index < items.len() => {
2232 let update = |(index, item)| {
2233 if index == next_index {
2234 update_field_path(item, &path[1..], replace)
2235 } else {
2236 Some(item.clone())
2237 }
2238 };
2239
2240 let items: Option<_> = items.iter().enumerate().map(update).collect();
2241 Some(Value::Tuple(items?))
2242 }
2243 _ => None,
2244 }
2245}
2246
2247fn is_updatable_in_place(env: &Env, expr: &Expr) -> (bool, bool) {
2248 match &expr.kind {
2249 ExprKind::Var(Res::Local(id), _) => match env.get(*id) {
2250 Some(var) => match &var.value {
2251 Value::Array(var) => (true, Rc::weak_count(var) + Rc::strong_count(var) == 1),
2252 _ => (false, false),
2253 },
2254 _ => (false, false),
2255 },
2256 _ => (false, false),
2257 }
2258}
2259
2260fn is_counting_call(name: &str) -> bool {
2261 matches!(
2262 name,
2263 "StartCountingOperation"
2264 | "StopCountingOperation"
2265 | "StartCountingFunction"
2266 | "StopCountingFunction"
2267 | "StartCountingQubits"
2268 | "StopCountingQubits"
2269 )
2270}
2271
2272fn make_counting_key(id: StoreItemId, functor: FunctorApp) -> CallableCountKey {
2273 (id, functor.adjoint, functor.controlled > 0)
2274}
2275
2276#[derive(Default)]
2277struct QubitCounter {
2278 seen: FxHashSet<usize>,
2279 count: i64,
2280}
2281
2282impl QubitCounter {
2283 fn allocated(&mut self, qubit: usize) {
2284 if self.seen.insert(qubit) {
2285 self.count += 1;
2286 }
2287 }
2288
2289 fn into_count(self) -> i64 {
2290 self.count
2291 }
2292}
2293