-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathinterpret.rs
1336 lines (1221 loc) · 44.2 KB
/
interpret.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#[cfg(test)]
mod circuit_tests;
mod debug;
#[cfg(test)]
mod debugger_tests;
#[cfg(test)]
mod package_tests;
#[cfg(test)]
mod tests;
use std::rc::Rc;
pub use qsc_eval::{
debug::Frame,
noise::PauliNoise,
output::{self, GenericReceiver},
val::Closure,
val::Range as ValueRange,
val::Result,
val::Value,
StepAction, StepResult,
};
use qsc_hir::{global, ty};
use qsc_linter::{HirLint, Lint, LintKind, LintLevel};
use qsc_lowerer::{map_fir_package_to_hir, map_hir_package_to_fir};
use qsc_partial_eval::ProgramEntry;
use qsc_rca::PackageStoreComputeProperties;
use crate::{
error::{self, WithStack},
incremental::Compiler,
location::Location,
};
use debug::format_call_stack;
use miette::Diagnostic;
use num_bigint::BigUint;
use num_complex::Complex;
use qsc_circuit::{
operations::entry_expr_for_qubit_operation, Builder as CircuitBuilder, Circuit,
Config as CircuitConfig,
};
use qsc_codegen::qir::{fir_to_qir, fir_to_qir_from_callable};
use qsc_data_structures::{
functors::FunctorApp,
language_features::LanguageFeatures,
line_column::{Encoding, Range},
span::Span,
target::TargetCapabilityFlags,
};
use qsc_eval::{
backend::{Backend, Chain as BackendChain, SparseSim},
output::Receiver,
val, Env, State, VariableInfo,
};
use qsc_fir::fir::{self, ExecGraph, Global, PackageStoreLookup};
use qsc_fir::{
fir::{Block, BlockId, Expr, ExprId, Package, PackageId, Pat, PatId, Stmt, StmtId},
visit::{self, Visitor},
};
use qsc_frontend::{
compile::{CompileUnit, Dependencies, PackageStore, Source, SourceMap},
error::WithSource,
incremental::Increment,
};
use qsc_passes::{PackageType, PassContext};
use rustc_hash::FxHashSet;
use thiserror::Error;
impl Error {
#[must_use]
pub fn stack_trace(&self) -> Option<&String> {
match &self {
Error::Eval(err) => err.stack_trace(),
_ => None,
}
}
}
#[derive(Clone, Debug, Diagnostic, Error)]
pub enum Error {
#[error(transparent)]
#[diagnostic(transparent)]
Compile(#[from] crate::compile::Error),
#[error(transparent)]
#[diagnostic(transparent)]
Pass(#[from] WithSource<qsc_passes::Error>),
#[error("runtime error")]
#[diagnostic(transparent)]
Eval(#[from] WithStack<WithSource<qsc_eval::Error>>),
#[error("circuit error")]
#[diagnostic(transparent)]
Circuit(#[from] qsc_circuit::Error),
#[error("entry point not found")]
#[diagnostic(code("Qsc.Interpret.NoEntryPoint"))]
NoEntryPoint,
#[error("unsupported runtime capabilities for code generation")]
#[diagnostic(code("Qsc.Interpret.UnsupportedRuntimeCapabilities"))]
UnsupportedRuntimeCapabilities,
#[error("expression does not evaluate to an operation")]
#[diagnostic(code("Qsc.Interpret.NotAnOperation"))]
#[diagnostic(help("provide the name of a callable or a lambda expression"))]
NotAnOperation,
#[error("value is not a global callable")]
#[diagnostic(code("Qsc.Interpret.NotACallable"))]
NotACallable,
#[error("partial evaluation error")]
#[diagnostic(transparent)]
PartialEvaluation(#[from] WithSource<qsc_partial_eval::Error>),
}
/// A Q# interpreter.
pub struct Interpreter {
/// The incremental Q# compiler.
compiler: Compiler,
/// The target capabilities used for compilation.
capabilities: TargetCapabilityFlags,
/// The number of lines that have so far been compiled.
/// This field is used to generate a unique label
/// for each line evaluated with `eval_fragments`.
lines: u32,
// The FIR store
fir_store: fir::PackageStore,
/// FIR lowerer
lowerer: qsc_lowerer::Lowerer,
/// The execution graph for the last expression evaluated.
expr_graph: Option<ExecGraph>,
/// The ID of the current package.
/// This ID is valid both for the FIR store and the `PackageStore`.
package: PackageId,
/// The ID of the source package. The source package
/// is made up of the initial sources passed in when creating the interpreter.
/// This ID is valid both for the FIR store and the `PackageStore`.
source_package: PackageId,
/// The default simulator backend.
sim: BackendChain<SparseSim, CircuitBuilder>,
/// The quantum seed, if any. This is cached here so that it can be used in calls to
/// `run_internal` which use a passed instance of the simulator instead of the one above.
quantum_seed: Option<u64>,
/// The classical seed, if any. This needs to be passed to the evaluator for use in intrinsic
/// calls that produce classical random numbers.
classical_seed: Option<u64>,
/// The evaluator environment.
env: Env,
}
pub type InterpretResult = std::result::Result<Value, Vec<Error>>;
impl Interpreter {
/// Creates a new incremental compiler, compiling the passed in sources.
/// # Errors
/// If compiling the sources fails, compiler errors are returned.
pub fn new(
sources: SourceMap,
package_type: PackageType,
capabilities: TargetCapabilityFlags,
language_features: LanguageFeatures,
store: PackageStore,
dependencies: &Dependencies,
) -> std::result::Result<Self, Vec<Error>> {
Self::new_internal(
false,
sources,
package_type,
capabilities,
language_features,
store,
dependencies,
)
}
/// Creates a new incremental compiler with debugging stmts enabled, compiling the passed in sources.
/// # Errors
/// If compiling the sources fails, compiler errors are returned.
pub fn new_with_debug(
sources: SourceMap,
package_type: PackageType,
capabilities: TargetCapabilityFlags,
language_features: LanguageFeatures,
store: PackageStore,
dependencies: &Dependencies,
) -> std::result::Result<Self, Vec<Error>> {
Self::new_internal(
true,
sources,
package_type,
capabilities,
language_features,
store,
dependencies,
)
}
fn new_internal(
dbg: bool,
sources: SourceMap,
package_type: PackageType,
capabilities: TargetCapabilityFlags,
language_features: LanguageFeatures,
store: PackageStore,
dependencies: &Dependencies,
) -> std::result::Result<Self, Vec<Error>> {
let compiler = Compiler::new(
sources,
package_type,
capabilities,
language_features,
store,
dependencies,
)
.map_err(into_errors)?;
let mut fir_store = fir::PackageStore::new();
for (id, unit) in compiler.package_store() {
let pkg = qsc_lowerer::Lowerer::new()
.with_debug(dbg)
.lower_package(&unit.package, &fir_store);
fir_store.insert(map_hir_package_to_fir(id), pkg);
}
let source_package_id = compiler.source_package_id();
let package_id = compiler.package_id();
let package = map_hir_package_to_fir(package_id);
if capabilities != TargetCapabilityFlags::all() {
let _ = PassContext::run_fir_passes_on_fir(
&fir_store,
map_hir_package_to_fir(source_package_id),
capabilities,
)
.map_err(|caps_errors| {
let source_package = compiler
.package_store()
.get(source_package_id)
.expect("package should exist in the package store");
caps_errors
.into_iter()
.map(|error| Error::Pass(WithSource::from_map(&source_package.sources, error)))
.collect::<Vec<_>>()
})?;
}
Ok(Self {
compiler,
lines: 0,
capabilities,
fir_store,
lowerer: qsc_lowerer::Lowerer::new().with_debug(dbg),
expr_graph: None,
env: Env::default(),
sim: sim_circuit_backend(),
quantum_seed: None,
classical_seed: None,
package,
source_package: map_hir_package_to_fir(source_package_id),
})
}
pub fn from(
store: PackageStore,
source_package_id: qsc_hir::hir::PackageId,
capabilities: TargetCapabilityFlags,
language_features: LanguageFeatures,
dependencies: &Dependencies,
) -> std::result::Result<Self, Vec<Error>> {
let compiler = Compiler::from(
store,
source_package_id,
capabilities,
language_features,
dependencies,
)
.map_err(into_errors)?;
let mut fir_store = fir::PackageStore::new();
for (id, unit) in compiler.package_store() {
let mut lowerer = qsc_lowerer::Lowerer::new();
let pkg = lowerer.lower_package(&unit.package, &fir_store);
fir_store.insert(map_hir_package_to_fir(id), pkg);
}
let source_package_id = compiler.source_package_id();
let package_id = compiler.package_id();
let package = map_hir_package_to_fir(package_id);
if capabilities != TargetCapabilityFlags::all() {
let _ = PassContext::run_fir_passes_on_fir(
&fir_store,
map_hir_package_to_fir(source_package_id),
capabilities,
)
.map_err(|caps_errors| {
let source_package = compiler
.package_store()
.get(source_package_id)
.expect("package should exist in the package store");
caps_errors
.into_iter()
.map(|error| Error::Pass(WithSource::from_map(&source_package.sources, error)))
.collect::<Vec<_>>()
})?;
}
Ok(Self {
compiler,
lines: 0,
capabilities,
fir_store,
lowerer: qsc_lowerer::Lowerer::new(),
expr_graph: None,
env: Env::default(),
sim: sim_circuit_backend(),
quantum_seed: None,
classical_seed: None,
package,
source_package: map_hir_package_to_fir(source_package_id),
})
}
/// Given a package ID, returns all the global items in the package.
/// Note this does not currently include re-exports.
fn package_globals(&self, package_id: PackageId) -> Vec<(Vec<Rc<str>>, Rc<str>, Value)> {
let mut exported_items = Vec::new();
let package = &self
.compiler
.package_store()
.get(map_fir_package_to_hir(package_id))
.expect("package should exist in the package store")
.package;
for global in global::iter_package(Some(map_fir_package_to_hir(package_id)), package) {
if let global::Kind::Term(term) = global.kind {
let store_item_id = fir::StoreItemId {
package: package_id,
item: fir::LocalItemId::from(usize::from(term.id.item)),
};
exported_items.push((
global.namespace,
global.name,
Value::Global(store_item_id, FunctorApp::default()),
));
}
}
exported_items
}
/// Get the global callables defined in the user source passed into initialization of the interpreter as `Value` instances.
pub fn user_globals(&self) -> Vec<(Vec<Rc<str>>, Rc<str>, Value)> {
self.package_globals(self.source_package)
}
/// Get the global callables defined in the open package being interpreted as `Value` instances, which will include any items
/// defined by calls to `eval_fragments` and the like.
pub fn source_globals(&self) -> Vec<(Vec<Rc<str>>, Rc<str>, Value)> {
self.package_globals(self.package)
}
/// Get the input and output types of a given value representing a global item.
/// # Panics
/// Panics if the item is not callable or a type that can be invoked as a callable.
pub fn global_tys(&self, item_id: &Value) -> Option<(ty::Ty, ty::Ty)> {
let Value::Global(item_id, _) = item_id else {
panic!("value is not a global callable");
};
let package_id = map_fir_package_to_hir(item_id.package);
let unit = self
.compiler
.package_store()
.get(package_id)
.expect("package should exist in the package store");
let item = unit
.package
.items
.get(qsc_hir::hir::LocalItemId::from(usize::from(item_id.item)))?;
match &item.kind {
qsc_hir::hir::ItemKind::Callable(decl) => {
Some((decl.input.ty.clone(), decl.output.clone()))
}
qsc_hir::hir::ItemKind::Ty(_, udt) => {
// We don't handle UDTs, so we return an error type that prevents later code from processing this item.
Some((udt.get_pure_ty(), ty::Ty::Err))
}
_ => panic!("item is not callable"),
}
}
pub fn set_quantum_seed(&mut self, seed: Option<u64>) {
self.quantum_seed = seed;
self.sim.set_seed(seed);
}
pub fn set_classical_seed(&mut self, seed: Option<u64>) {
self.classical_seed = seed;
}
pub fn check_source_lints(&self) -> Vec<Lint> {
if let Some(compile_unit) = self
.compiler
.package_store()
.get(self.compiler.source_package_id())
{
qsc_linter::run_lints(
self.compiler.package_store(),
compile_unit,
// see https://github.com/microsoft/qsharp/pull/1627 for context
// on why we override this config
Some(&[qsc_linter::LintConfig {
kind: LintKind::Hir(HirLint::NeedlessOperation),
level: LintLevel::Warn,
}]),
)
} else {
Vec::new()
}
}
/// Executes the entry expression until the end of execution.
/// # Errors
/// Returns a vector of errors if evaluating the entry point fails.
pub fn eval_entry(&mut self, receiver: &mut impl Receiver) -> InterpretResult {
let graph = self.get_entry_exec_graph()?;
self.expr_graph = Some(graph.clone());
eval(
self.source_package,
self.classical_seed,
graph,
self.compiler.package_store(),
&self.fir_store,
&mut Env::default(),
&mut self.sim,
receiver,
)
}
/// Executes the entry expression until the end of execution, using the given simulator backend
/// and a new instance of the environment.
pub fn eval_entry_with_sim(
&mut self,
sim: &mut impl Backend<ResultType = impl Into<val::Result>>,
receiver: &mut impl Receiver,
) -> InterpretResult {
let graph = self.get_entry_exec_graph()?;
self.expr_graph = Some(graph.clone());
if self.quantum_seed.is_some() {
sim.set_seed(self.quantum_seed);
}
eval(
self.source_package,
self.classical_seed,
graph,
self.compiler.package_store(),
&self.fir_store,
&mut Env::default(),
sim,
receiver,
)
}
fn get_entry_exec_graph(&self) -> std::result::Result<ExecGraph, Vec<Error>> {
let unit = self.fir_store.get(self.source_package);
if unit.entry.is_some() {
return Ok(unit.entry_exec_graph.clone());
};
Err(vec![Error::NoEntryPoint])
}
/// # Errors
/// If the parsing of the fragments fails, an error is returned.
/// If the compilation of the fragments fails, an error is returned.
/// If there is a runtime error when interpreting the fragments, an error is returned.
pub fn eval_fragments(
&mut self,
receiver: &mut impl Receiver,
fragments: &str,
) -> InterpretResult {
let label = self.next_line_label();
let mut increment = self
.compiler
.compile_fragments_fail_fast(&label, fragments)
.map_err(into_errors)?;
// Clear the entry expression, as we are evaluating fragments and a fragment with a `@EntryPoint` attribute
// should not change what gets executed.
increment.clear_entry();
self.eval_increment(receiver, increment)
}
/// It is assumed that if there were any parse errors on the fragments, the caller would have
/// already handled them. This function is intended to be used in cases where the caller wants
/// to handle the parse errors themselves.
/// # Errors
/// If the compilation of the fragments fails, an error is returned.
/// If there is a runtime error when interpreting the fragments, an error is returned.
pub fn eval_ast_fragments(
&mut self,
receiver: &mut impl Receiver,
fragments: &str,
package: qsc_ast::ast::Package,
) -> InterpretResult {
let label = self.next_line_label();
let increment = self
.compiler
.compile_ast_fragments_fail_fast(&label, fragments, package)
.map_err(into_errors)?;
self.eval_increment(receiver, increment)
}
fn eval_increment(
&mut self,
receiver: &mut impl Receiver,
increment: Increment,
) -> InterpretResult {
let (graph, _) = self.lower(&increment)?;
self.expr_graph = Some(graph.clone());
// Updating the compiler state with the new AST/HIR nodes
// is not necessary for the interpreter to function, as all
// the state required for evaluation already exists in the
// FIR store. It could potentially save some memory
// *not* to do hold on to the AST/HIR, but it is done
// here to keep the package stores consistent.
self.compiler.update(increment);
eval(
self.package,
self.classical_seed,
graph,
self.compiler.package_store(),
&self.fir_store,
&mut self.env,
&mut self.sim,
receiver,
)
}
/// Invokes the given callable with the given arguments using the current environment, simlator, and compilation.
pub fn invoke(
&mut self,
receiver: &mut impl Receiver,
callable: Value,
args: Value,
) -> InterpretResult {
qsc_eval::invoke(
self.package,
self.classical_seed,
&self.fir_store,
&mut self.env,
&mut self.sim,
receiver,
callable,
args,
)
.map_err(|(error, call_stack)| {
eval_error(
self.compiler.package_store(),
&self.fir_store,
call_stack,
error,
)
})
}
// Invokes the given callable with the given arguments using the current environment and compilation but with a fresh
// simulator configured with the given noise, if any.
pub fn invoke_with_noise(
&mut self,
receiver: &mut impl Receiver,
callable: Value,
args: Value,
noise: Option<PauliNoise>,
) -> InterpretResult {
let mut sim = match noise {
Some(noise) => SparseSim::new_with_noise(&noise),
None => SparseSim::new(),
};
qsc_eval::invoke(
self.package,
self.classical_seed,
&self.fir_store,
&mut self.env,
&mut sim,
receiver,
callable,
args,
)
.map_err(|(error, call_stack)| {
eval_error(
self.compiler.package_store(),
&self.fir_store,
call_stack,
error,
)
})
}
/// Runs the given entry expression on a new instance of the environment and simulator,
/// but using the current compilation.
pub fn run(
&mut self,
receiver: &mut impl Receiver,
expr: Option<&str>,
noise: Option<PauliNoise>,
) -> InterpretResult {
let mut sim = match noise {
Some(noise) => SparseSim::new_with_noise(&noise),
None => SparseSim::new(),
};
self.run_with_sim(&mut sim, receiver, expr)
}
/// Gets the current quantum state of the simulator.
pub fn get_quantum_state(&mut self) -> (Vec<(BigUint, Complex<f64>)>, usize) {
self.sim.capture_quantum_state()
}
/// Get the current circuit representation of the program.
pub fn get_circuit(&self) -> Circuit {
self.sim.chained.snapshot()
}
/// Performs QIR codegen using the given entry expression on a new instance of the environment
/// and simulator but using the current compilation.
pub fn qirgen(&mut self, expr: &str) -> std::result::Result<String, Vec<Error>> {
if self.capabilities == TargetCapabilityFlags::all() {
return Err(vec![Error::UnsupportedRuntimeCapabilities]);
}
// Compile the expression. This operation will set the expression as
// the entry-point in the FIR store.
let (graph, compute_properties) = self.compile_entry_expr(expr)?;
let Some(compute_properties) = compute_properties else {
// This can only happen if capability analysis was not run. This would be a bug
// and we are in a bad state and can't proceed.
panic!("internal error: compute properties not set after lowering entry expression");
};
let package = self.fir_store.get(self.package);
let entry = ProgramEntry {
exec_graph: graph,
expr: (
self.package,
package
.entry
.expect("package must have an entry expression"),
)
.into(),
};
// Generate QIR
fir_to_qir(
&self.fir_store,
self.capabilities,
Some(compute_properties),
&entry,
)
.map_err(|e| {
let hir_package_id = match e.span() {
Some(span) => span.package,
None => map_fir_package_to_hir(self.package),
};
let source_package = self
.compiler
.package_store()
.get(hir_package_id)
.expect("package should exist in the package store");
vec![Error::PartialEvaluation(WithSource::from_map(
&source_package.sources,
e,
))]
})
}
/// Performs QIR codegen using the given callable with the given arguments on a new instance of the environment
/// and simulator but using the current compilation.
pub fn qirgen_from_callable(
&mut self,
callable: &Value,
args: Value,
) -> std::result::Result<String, Vec<Error>> {
if self.capabilities == TargetCapabilityFlags::all() {
return Err(vec![Error::UnsupportedRuntimeCapabilities]);
}
let Value::Global(store_item_id, _) = callable else {
return Err(vec![Error::NotACallable]);
};
fir_to_qir_from_callable(
&self.fir_store,
self.capabilities,
None,
*store_item_id,
args,
)
.map_err(|e| {
let hir_package_id = match e.span() {
Some(span) => span.package,
None => map_fir_package_to_hir(self.package),
};
let source_package = self
.compiler
.package_store()
.get(hir_package_id)
.expect("package should exist in the package store");
vec![Error::PartialEvaluation(WithSource::from_map(
&source_package.sources,
e,
))]
})
}
/// Generates a circuit representation for the program.
///
/// `entry` can be the current entrypoint, an entry expression, or any operation
/// that takes qubits.
///
/// An operation can be specified by its name or a lambda expression that only takes qubits.
/// e.g. `Sample.Main` , `qs => H(qs[0])`
///
/// If `simulate` is specified, the program is simulated and the resulting
/// circuit is returned (a.k.a. trace mode). Otherwise, the circuit is generated without
/// simulation. In this case circuit generation may fail if the program contains dynamic
/// behavior (quantum operations that are dependent on measurement results).
pub fn circuit(
&mut self,
entry: CircuitEntryPoint,
simulate: bool,
) -> std::result::Result<Circuit, Vec<Error>> {
let (entry_expr, invoke_params) = match entry {
CircuitEntryPoint::Operation(operation_expr) => {
let (item, functor_app) = self.eval_to_operation(&operation_expr)?;
let expr = entry_expr_for_qubit_operation(item, functor_app, &operation_expr)
.map_err(|e| vec![e.into()])?;
(Some(expr), None)
}
CircuitEntryPoint::EntryExpr(expr) => (Some(expr), None),
CircuitEntryPoint::Callable(call_val, args_val) => (None, Some((call_val, args_val))),
CircuitEntryPoint::EntryPoint => (None, None),
};
let circuit = if simulate {
let mut sim = sim_circuit_backend();
match invoke_params {
Some((callable, args)) => {
let mut sink = std::io::sink();
let mut out = GenericReceiver::new(&mut sink);
self.invoke_with_sim(&mut sim, &mut out, callable, args)?
}
None => self.run_with_sim_no_output(entry_expr, &mut sim)?,
};
sim.chained.finish()
} else {
let mut sim = CircuitBuilder::new(CircuitConfig {
base_profile: self.capabilities.is_empty(),
});
match invoke_params {
Some((callable, args)) => {
let mut sink = std::io::sink();
let mut out = GenericReceiver::new(&mut sink);
self.invoke_with_sim(&mut sim, &mut out, callable, args)?
}
None => self.run_with_sim_no_output(entry_expr, &mut sim)?,
};
sim.finish()
};
Ok(circuit)
}
/// Sets the entry expression for the interpreter.
pub fn set_entry_expr(&mut self, entry_expr: &str) -> std::result::Result<(), Vec<Error>> {
let (graph, _) = self.compile_entry_expr(entry_expr)?;
self.expr_graph = Some(graph);
Ok(())
}
/// Runs the given entry expression on the given simulator with a new instance of the environment
/// but using the current compilation.
pub fn run_with_sim(
&mut self,
sim: &mut impl Backend<ResultType = impl Into<val::Result>>,
receiver: &mut impl Receiver,
expr: Option<&str>,
) -> InterpretResult {
let graph = if let Some(expr) = expr {
let (graph, _) = self.compile_entry_expr(expr)?;
self.expr_graph = Some(graph.clone());
graph
} else {
self.expr_graph.clone().ok_or(vec![Error::NoEntryPoint])?
};
if self.quantum_seed.is_some() {
sim.set_seed(self.quantum_seed);
}
eval(
self.package,
self.classical_seed,
graph,
self.compiler.package_store(),
&self.fir_store,
&mut Env::default(),
sim,
receiver,
)
}
fn run_with_sim_no_output(
&mut self,
entry_expr: Option<String>,
sim: &mut impl Backend<ResultType = impl Into<val::Result>>,
) -> InterpretResult {
let mut sink = std::io::sink();
let mut out = GenericReceiver::new(&mut sink);
let (package_id, graph) = if let Some(entry_expr) = entry_expr {
// entry expression is provided
(self.package, self.compile_entry_expr(&entry_expr)?.0)
} else {
// no entry expression, use the entrypoint in the package
(self.source_package, self.get_entry_exec_graph()?)
};
self.expr_graph = Some(graph.clone());
if self.quantum_seed.is_some() {
sim.set_seed(self.quantum_seed);
}
eval(
package_id,
self.classical_seed,
graph,
self.compiler.package_store(),
&self.fir_store,
&mut Env::default(),
sim,
&mut out,
)
}
/// Invokes the given callable with the given arguments on the given simulator with a new instance of the environment
/// but using the current compilation.
pub fn invoke_with_sim(
&mut self,
sim: &mut impl Backend<ResultType = impl Into<val::Result>>,
receiver: &mut impl Receiver,
callable: Value,
args: Value,
) -> InterpretResult {
qsc_eval::invoke(
self.package,
self.classical_seed,
&self.fir_store,
&mut Env::default(),
sim,
receiver,
callable,
args,
)
.map_err(|(error, call_stack)| {
eval_error(
self.compiler.package_store(),
&self.fir_store,
call_stack,
error,
)
})
}
fn compile_entry_expr(
&mut self,
expr: &str,
) -> std::result::Result<(ExecGraph, Option<PackageStoreComputeProperties>), Vec<Error>> {
let increment = self
.compiler
.compile_entry_expr(expr)
.map_err(into_errors)?;
// `lower` will update the entry expression in the FIR store,
// and it will always return an empty list of statements.
let (graph, compute_properties) = self.lower(&increment)?;
// The AST and HIR packages in `increment` only contain an entry
// expression and no statements. The HIR *can* contain items if the entry
// expression defined any items.
assert!(increment.hir.stmts.is_empty());
assert!(increment.ast.package.nodes.is_empty());
// Updating the compiler state with the new AST/HIR nodes
// is not necessary for the interpreter to function, as all
// the state required for evaluation already exists in the
// FIR store. It could potentially save some memory
// *not* to do hold on to the AST/HIR, but it is done
// here to keep the package stores consistent.
self.compiler.update(increment);
Ok((graph, compute_properties))
}
fn lower(
&mut self,
unit_addition: &qsc_frontend::incremental::Increment,
) -> core::result::Result<(ExecGraph, Option<PackageStoreComputeProperties>), Vec<Error>> {
if self.capabilities != TargetCapabilityFlags::all() {
return self.run_fir_passes(unit_addition);
}
self.lower_and_update_package(unit_addition);
Ok((self.lowerer.take_exec_graph().into(), None))
}
fn lower_and_update_package(&mut self, unit: &qsc_frontend::incremental::Increment) {
{
let fir_package = self.fir_store.get_mut(self.package);
self.lowerer
.lower_and_update_package(fir_package, &unit.hir);
}
let fir_package: &Package = self.fir_store.get(self.package);
qsc_fir::validate::validate(fir_package, &self.fir_store);
}
fn run_fir_passes(
&mut self,
unit: &qsc_frontend::incremental::Increment,
) -> std::result::Result<(ExecGraph, Option<PackageStoreComputeProperties>), Vec<Error>> {
self.lower_and_update_package(unit);
let cap_results =
PassContext::run_fir_passes_on_fir(&self.fir_store, self.package, self.capabilities);
let compute_properties = cap_results.map_err(|caps_errors| {
// if there are errors, convert them to interpreter errors
// and revert the update to the lowerer/FIR store.
let fir_package = self.fir_store.get_mut(self.package);
self.lowerer.revert_last_increment(fir_package);
let source_package = self
.compiler
.package_store()
.get(map_fir_package_to_hir(self.package))
.expect("package should exist in the package store");
caps_errors
.into_iter()
.map(|error| Error::Pass(WithSource::from_map(&source_package.sources, error)))
.collect::<Vec<_>>()
})?;
let graph = self.lowerer.take_exec_graph();
Ok((graph.into(), Some(compute_properties)))
}
fn next_line_label(&mut self) -> String {
let label = format!("line_{}", self.lines);
self.lines += 1;
label
}
/// Evaluate the name of an operation, or any expression that evaluates to a callable,
/// and return the Item ID and function application for the callable.
/// Examples: "Microsoft.Quantum.Diagnostics.DumpMachine", "(qs: Qubit[]) => H(qs[0])",
/// "Controlled SWAP"
fn eval_to_operation(
&mut self,
operation_expr: &str,
) -> std::result::Result<(&qsc_hir::hir::Item, FunctorApp), Vec<Error>> {
let mut sink = std::io::sink();
let mut out = GenericReceiver::new(&mut sink);
let (store_item_id, functor_app) = match self.eval_fragments(&mut out, operation_expr)? {
Value::Closure(b) => (b.id, b.functor),
Value::Global(item_id, functor_app) => (item_id, functor_app),
_ => return Err(vec![Error::NotAnOperation]),
};
let package = map_fir_package_to_hir(store_item_id.package);
let local_item_id = crate::hir::LocalItemId::from(usize::from(store_item_id.item));
let unit = self
.compiler
.package_store()
.get(package)
.expect("package should exist in the package store");
let item = unit
.package
.items
.get(local_item_id)
.expect("item should exist in the package");
Ok((item, functor_app))
}
}