-
Notifications
You must be signed in to change notification settings - Fork 208
Expand file tree
/
Copy pathlib.rs
More file actions
4445 lines (4137 loc) · 176 KB
/
Copy pathlib.rs
File metadata and controls
4445 lines (4137 loc) · 176 KB
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.
//! The Q# partial evaluator residualizes a Q# program, producing RIR from FIR.
//! It does this by evaluating all purely classical expressions and generating RIR instructions for expressions that are
//! not purely classical.
#[cfg(test)]
mod tests;
mod evaluation_context;
mod management;
use core::panic;
use evaluation_context::{Arg, BlockNode, EvalControlFlow, EvaluationContext, Scope};
use management::{QuantumIntrinsicsChecker, ResourceManager};
use miette::Diagnostic;
use qsc_data_structures::{functors::FunctorApp, span::Span, target::TargetCapabilityFlags};
use qsc_eval::{
self, Error as EvalError, ErrorBehavior, PackageSpan, State, StepAction, StepResult, Variable,
are_ctls_unique,
backend::TracingBackend,
intrinsic::qubit_relabel,
output::GenericReceiver,
resolve_closure,
val::{
self, Value, Var, VarTy, index_array, slice_array, update_functor_app, update_index_range,
update_index_single,
},
};
use qsc_fir::{
fir::{
self, BinOp, Block, BlockId, CallableDecl, CallableImpl, ExecGraph, ExecGraphConfig, Expr,
ExprId, ExprKind, Field, Global, Ident, LocalVarId, Mutability, PackageId, PackageStore,
PackageStoreLookup, Pat, PatId, PatKind, PrimField, Res, SpecDecl, SpecImpl, Stmt, StmtId,
StmtKind, StoreBlockId, StoreExprId, StoreItemId, StorePatId, StoreStmtId, StringComponent,
UnOp,
},
ty::{Prim, Ty},
};
use qsc_lowerer::map_fir_package_to_hir;
use qsc_rca::{
ComputeKind, ComputePropertiesLookup, ItemComputeProperties, PackageStoreComputeProperties,
RuntimeFeatureFlags, ValueKind,
errors::{
Error as CapabilityError, generate_errors_from_runtime_features,
get_missing_runtime_features,
},
};
pub use qsc_rir::{
builder::{self, initialize_decl},
debug::{
DbgLocation, DbgLocationId, DbgPackageOffset, DbgScope, DbgScopeId, InstructionDbgMetadata,
},
rir::{
self, Callable, CallableId, CallableType, ConditionCode, FcmpConditionCode, Instruction,
Literal, Operand, Program, VariableId,
},
};
use rustc_hash::FxHashMap;
use std::{collections::hash_map::Entry, rc::Rc, result::Result};
use thiserror::Error;
/// Partially evaluates a program with the specified entry expression.
pub fn partially_evaluate(
package_store: &PackageStore,
compute_properties: &PackageStoreComputeProperties,
entry: &ProgramEntry,
capabilities: TargetCapabilityFlags,
config: PartialEvalConfig,
) -> Result<Program, Error> {
let partial_evaluator = PartialEvaluator::new(
package_store,
compute_properties,
entry,
capabilities,
config,
);
partial_evaluator.eval()
}
/// Partially evaluates a callable with the specified arguments.
pub fn partially_evaluate_call(
package_store: &PackageStore,
compute_properties: &PackageStoreComputeProperties,
callable: StoreItemId,
args: Value,
capabilities: TargetCapabilityFlags,
config: PartialEvalConfig,
) -> Result<Program, Error> {
let partial_evaluator = PartialEvaluator::new_from_package_id(
package_store,
compute_properties,
callable.package,
capabilities,
config,
);
partial_evaluator.invoke(callable, args)
}
/// A partial evaluation error.
#[derive(Clone, Debug, Diagnostic, Error)]
pub enum Error {
#[error(transparent)]
#[diagnostic(transparent)]
CapabilityError(CapabilityError),
#[error("cannot use a dynamic value returned from a runtime-resolved callable")]
#[diagnostic(code("Qsc.PartialEval.UnexpectedDynamicValue"))]
#[diagnostic(help("try invoking the desired callable directly"))]
UnexpectedDynamicValue(#[label] PackageSpan),
#[error("unsupported type `{0}` in custom intrinsic callable")]
#[diagnostic(help(
"variables of type `{0}` cannot be emitted into QIR and should not appear in custom intrinsic callable signatures"
))]
#[diagnostic(code("Qsc.PartialEval.UnsupportedType"))]
UnsupportedCustomIntrinsicType(String, #[label] PackageSpan),
#[error("partial evaluation failed with error: {0}")]
#[diagnostic(code("Qsc.PartialEval.EvaluationFailed"))]
EvaluationFailed(String, #[label] PackageSpan),
#[error("unsupported Result literal in output")]
#[diagnostic(help(
"Result literals `One` and `Zero` cannot be included in generated QIR output recording."
))]
#[diagnostic(code("Qsc.PartialEval.OutputResultLiteral"))]
OutputResultLiteral(#[label] PackageSpan),
#[error("an unexpected error occurred related to: {0}")]
#[diagnostic(code("Qsc.PartialEval.Unexpected"))]
#[diagnostic(help(
"this is probably a bug, please consider reporting this as an issue to the development team"
))]
Unexpected(String, #[label] PackageSpan),
#[error("failed to evaluate: {0} is not supported")]
#[diagnostic(code("Qsc.PartialEval.Unimplemented"))]
Unimplemented(String, #[label] PackageSpan),
#[error("unsupported call into test callable")]
#[diagnostic(code("Qsc.PartialEval.UnsupportedTestCallable"))]
#[diagnostic(help(
"callables with the `@Test` annotation should not be called from non-test code."
))]
UnsupportedTestCallable(#[label] PackageSpan),
#[error("unsupported use of simulation-only intrinsic `{0}`")]
#[diagnostic(code("Qsc.PartialEval.UnsupportedSimulationIntrinsic"))]
UnsupportedSimulationIntrinsic(String, #[label] PackageSpan),
}
impl From<EvalError> for Error {
fn from(e: EvalError) -> Self {
Error::EvaluationFailed(e.to_string(), *e.span())
}
}
impl Error {
#[must_use]
pub fn span(&self) -> Option<PackageSpan> {
match self {
Self::CapabilityError(_) => None,
Self::UnexpectedDynamicValue(span)
| Self::UnsupportedCustomIntrinsicType(_, span)
| Self::EvaluationFailed(_, span)
| Self::OutputResultLiteral(span)
| Self::Unexpected(_, span)
| Self::Unimplemented(_, span)
| Self::UnsupportedTestCallable(span)
| Self::UnsupportedSimulationIntrinsic(_, span) => Some(*span),
}
}
}
/// An entry to the program to be partially evaluated.
pub struct ProgramEntry {
/// The execution graph that corresponds to the entry expression.
pub exec_graph: ExecGraph,
/// The entry expression unique identifier within a package store.
pub expr: fir::StoreExprId,
}
struct PartialEvaluator<'a> {
package_store: &'a PackageStore,
compute_properties: &'a PackageStoreComputeProperties,
resource_manager: ResourceManager,
backend: QuantumIntrinsicsChecker,
callables_map: FxHashMap<Rc<str>, CallableId>,
eval_context: EvaluationContext,
program: Program,
entry: Option<&'a ProgramEntry>,
config: PartialEvalConfig,
dbg_context: DbgContext,
}
#[derive(Clone, Copy)]
pub struct PartialEvalConfig {
pub generate_debug_metadata: bool,
}
impl<'a> PartialEvaluator<'a> {
fn new(
package_store: &'a PackageStore,
compute_properties: &'a PackageStoreComputeProperties,
entry: &'a ProgramEntry,
capabilities: TargetCapabilityFlags,
config: PartialEvalConfig,
) -> Self {
Self::new_internal(
package_store,
compute_properties,
capabilities,
Some(entry),
None,
config,
)
}
fn new_from_package_id(
package_store: &'a PackageStore,
compute_properties: &'a PackageStoreComputeProperties,
package_id: PackageId,
capabilities: TargetCapabilityFlags,
config: PartialEvalConfig,
) -> Self {
Self::new_internal(
package_store,
compute_properties,
capabilities,
None,
Some(package_id),
config,
)
}
fn new_internal(
package_store: &'a PackageStore,
compute_properties: &'a PackageStoreComputeProperties,
capabilities: TargetCapabilityFlags,
entry: Option<&'a ProgramEntry>,
package_id: Option<PackageId>,
config: PartialEvalConfig,
) -> Self {
// Create the entry-point callable.
let mut resource_manager = ResourceManager::default();
let mut program = Program::new();
program.config.capabilities = capabilities;
let entry_block_id = resource_manager.next_block();
program.blocks.insert(entry_block_id, rir::Block::default());
let entry_point_id = resource_manager.next_callable();
let entry_point = rir::Callable {
name: "main".into(),
input_type: Vec::new(),
output_type: Some(rir::Ty::Prim(rir::Prim::Integer)),
body: Some(entry_block_id),
call_type: CallableType::Regular,
};
program.callables.insert(entry_point_id, entry_point);
program.entry = entry_point_id;
// Add the required call to the initialization function.
let init_func = initialize_decl();
let init_id = resource_manager.next_callable();
program.callables.insert(init_id, init_func);
program
.get_block_mut(entry_block_id)
.0
.push(Instruction::Call(
init_id,
vec![Operand::Literal(Literal::NullPointer)],
None,
None,
));
// Initialize the evaluation context and create a new partial evaluator.
let context = EvaluationContext::new(
package_id.unwrap_or_else(|| {
entry
.expect("program entry should be provided when package id is None")
.expr
.package
}),
entry_block_id,
);
Self {
package_store,
compute_properties,
eval_context: context,
resource_manager,
backend: QuantumIntrinsicsChecker::default(),
callables_map: FxHashMap::default(),
program,
entry,
config,
dbg_context: Default::default(),
}
}
fn bind_value_to_pat(&mut self, mutability: Mutability, pat_id: PatId, value: Value) {
let pat = self.get_pat(pat_id);
match &pat.kind {
PatKind::Bind(ident) => {
self.bind_value_to_ident(mutability, ident, value);
}
PatKind::Tuple(pats) => {
let tuple = value.unwrap_tuple();
assert!(pats.len() == tuple.len());
for (pat_id, value) in pats.iter().zip(tuple.iter()) {
self.bind_value_to_pat(mutability, *pat_id, value.clone());
}
}
PatKind::Discard => {
// Nothing to bind to.
}
}
}
fn bind_value_to_ident(&mut self, mutability: Mutability, ident: &Ident, value: Value) {
// We do slightly different things depending on the mutability of the identifier.
match mutability {
Mutability::Mutable => self.bind_value_to_mutable_ident(ident, value),
Mutability::Immutable => {
let current_scope = self.eval_context.get_current_scope();
if matches!(value, Value::Var(var) if current_scope.get_static_value(var.id.into()).is_none())
{
// An immutable identifier is being bound to a dynamic value, so treat the identifier as mutable.
// This allows it to represent a point-in-time copy of the mutable value during evaluation.
self.bind_value_to_mutable_ident(ident, value);
} else {
// The value is static, so bind it to the classical map.
self.bind_value_to_immutable_ident(ident, value);
}
}
}
}
fn bind_value_to_immutable_ident(&mut self, ident: &Ident, value: Value) {
// If the value is not a variable, bind it to the classical map.
if !matches!(value, Value::Var(_)) {
self.bind_value_in_classical_map(ident, &value);
}
// Always bind the value to the hybrid map.
self.bind_value_in_hybrid_map(ident, value);
}
fn bind_value_to_mutable_ident(&mut self, ident: &Ident, value: Value) {
// If the value is not a variable, bind it to the classical map.
if !matches!(value, Value::Var(_)) {
self.bind_value_in_classical_map(ident, &value);
}
// Always bind the value to the hybrid map but do it differently depending of the value type.
if let Some((var_id, literal)) = self.try_create_mutable_variable(ident.id, &value) {
// If the variable maps to a know static literal, track that mapping.
if let Some(literal) = literal {
self.eval_context
.get_current_scope_mut()
.insert_static_var_mapping(var_id, literal);
}
} else {
self.bind_value_in_hybrid_map(ident, value);
}
}
fn bind_value_in_classical_map(&mut self, ident: &Ident, value: &Value) {
// Create a variable and bind it to the classical environment.
let var = Variable {
name: ident.name.clone(),
value: value.clone(),
span: ident.span,
};
let scope = self.eval_context.get_current_scope_mut();
scope.env.bind_variable_in_top_frame(ident.id, var);
}
fn bind_value_in_hybrid_map(&mut self, ident: &Ident, value: Value) {
// Insert the value into the hybrid vars map.
self.eval_context
.get_current_scope_mut()
.insert_hybrid_local_value(ident.id, value);
}
fn create_intrinsic_callable(
&self,
store_item_id: StoreItemId,
callable_decl: &CallableDecl,
call_type: CallableType,
) -> Result<Callable, Error> {
let callable_package = self.package_store.get(store_item_id.package);
let name = callable_decl.name.name.to_string();
let mut input_type: Vec<rir::Ty> = Vec::new();
for input_param in &callable_package.derive_callable_input_params(callable_decl) {
input_type.push(map_fir_type_to_rir_type(&input_param.ty).map_err(|msg| {
Error::UnsupportedCustomIntrinsicType(
msg,
PackageSpan {
package: map_fir_package_to_hir(store_item_id.package),
span: self
.package_store
.get_pat((store_item_id.package, input_param.pat).into())
.span,
},
)
})?);
}
let output_type = if callable_decl.output == Ty::UNIT {
None
} else {
Some(
map_fir_type_to_rir_type(&callable_decl.output).map_err(|msg| {
Error::UnsupportedCustomIntrinsicType(
msg,
PackageSpan {
package: map_fir_package_to_hir(self.get_current_package_id()),
span: callable_decl.span,
},
)
})?,
)
};
let body = None;
let call_type = if name.eq("__quantum__qis__reset__body") {
CallableType::Reset
} else {
call_type
};
Ok(Callable {
name,
input_type,
output_type,
body,
call_type,
})
}
fn create_program_block(&mut self) -> rir::BlockId {
let block_id = self.resource_manager.next_block();
self.program.blocks.insert(block_id, rir::Block::default());
block_id
}
fn entry_expr_output_span(&self) -> PackageSpan {
let expr = self.get_expr(
self.entry
.expect("should have entry when getting entry expr span")
.expr
.expr,
);
let local_span = match &expr.kind {
// Special handling for compiler generated entry expressions that come from the `@EntryPoint`
// attributed callable.
ExprKind::Call(callee, _) if expr.span == Span::default() => {
self.get_expr(*callee).span
}
_ => expr.span,
};
let hir_package_id = map_fir_package_to_hir(
self.entry
.expect("should have entry when getting entry expr span")
.expr
.package,
);
PackageSpan {
package: hir_package_id,
span: local_span,
}
}
fn extract_program(
mut self,
ret_val: Value,
output_ty: &Ty,
output_span: PackageSpan,
) -> Result<Program, Error> {
let output_recording: Vec<Instruction> = self
.generate_output_recording_instructions(ret_val, output_ty, "")
.map_err(|()| Error::OutputResultLiteral(output_span))?;
// Insert the return expression and return the generated program.
let current_block = self.get_current_rir_block_mut();
current_block.0.extend(output_recording);
current_block.0.push(Instruction::Return);
// Set the number of qubits and results used by the program.
self.program.num_qubits = self
.resource_manager
.qubit_count()
.try_into()
.expect("qubits count should fit into a u32");
self.program.num_results = self
.resource_manager
.result_register_count()
.try_into()
.expect("results count should fit into a u32");
self.program.dbg_info.remove_unused_dbg_metadata();
Ok(self.program)
}
fn eval(mut self) -> Result<Program, Error> {
// Evaluate the entry-point expression.
let ret_val = self
.try_eval_expr(
self.entry
.expect("should have program entry on call to eval")
.expr
.expr,
)?
.into_value();
let output_ty = &self
.get_expr(
self.entry
.expect("should have program entry on call to eval")
.expr
.expr,
)
.ty;
let output_span = self.entry_expr_output_span();
self.extract_program(ret_val, output_ty, output_span)
}
fn invoke(mut self, callable: StoreItemId, args: Value) -> Result<Program, Error> {
// Evaluate the callalbe.
let ret_val = self.eval_global_call(callable, args)?.into_value();
let global = self
.package_store
.get_global(callable)
.expect("global not present");
let Global::Callable(callable_decl) = global else {
// Instruction generation for UDTs is not supported.
panic!("global is not a callable");
};
let output_ty = &callable_decl.output;
self.extract_program(
ret_val,
output_ty,
PackageSpan {
package: map_fir_package_to_hir(callable.package),
span: callable_decl.span,
},
)
}
fn eval_array_update_index(
&mut self,
array: &[Value],
index_expr_id: ExprId,
update_expr_id: ExprId,
) -> Result<Value, Error> {
// Try to evaluate the index and update expressions to get their value, short-circuiting execution if any of the
// expressions is a return.
let index_expr_package_span = self.get_expr_package_span(index_expr_id);
let index_control_flow = self.try_eval_expr(index_expr_id)?;
let EvalControlFlow::Continue(index_value) = index_control_flow else {
return Err(Error::Unexpected(
"embedded return in index expression".to_string(),
index_expr_package_span,
));
};
let update_control_flow = self.try_eval_expr(update_expr_id)?;
let EvalControlFlow::Continue(update_value) = update_control_flow else {
return Err(Error::Unexpected(
"embedded return in update expression".to_string(),
self.get_expr_package_span(update_expr_id),
));
};
// Set the value at the specified index or range.
let update_result = match index_value {
Value::Int(index) => {
update_index_single(array, index, update_value, index_expr_package_span)
}
Value::Range(range) => update_index_range(
array,
range.start,
range.step,
range.end,
update_value,
index_expr_package_span,
),
_ => panic!("invalid kind of value for index"),
};
let updated_array = update_result.map_err(Error::from)?;
Ok(updated_array)
}
fn eval_bin_op(
&mut self,
bin_op: BinOp,
lhs_value: Value,
rhs_expr_id: ExprId,
lhs_span: PackageSpan, // For diagnostic purposes only.
bin_op_expr_span: PackageSpan, // For diagnostic purposes only.
) -> Result<EvalControlFlow, Error> {
// Evaluate the binary operation differently depending on the LHS value variant.
match lhs_value {
Value::Array(lhs_array) => self.eval_bin_op_with_lhs_array_operand(
bin_op,
&lhs_array,
rhs_expr_id,
bin_op_expr_span,
),
Value::Result(lhs_result) => self.eval_bin_op_with_lhs_result_operand(
bin_op,
lhs_result,
rhs_expr_id,
bin_op_expr_span,
),
Value::Bool(lhs_bool) => {
self.eval_bin_op_with_lhs_classical_bool_operand(bin_op, lhs_bool, rhs_expr_id)
}
Value::Int(lhs_int) => {
let lhs_operand = Operand::Literal(Literal::Integer(lhs_int));
self.eval_bin_op_with_lhs_integer_operand(
bin_op,
lhs_operand,
rhs_expr_id,
bin_op_expr_span,
)
}
Value::Double(lhs_double) => {
let lhs_operand = Operand::Literal(Literal::Double(lhs_double));
self.eval_bin_op_with_lhs_double_operand(
bin_op,
lhs_operand,
rhs_expr_id,
bin_op_expr_span,
)
}
Value::Var(lhs_eval_var) => {
self.eval_bin_op_with_lhs_var(bin_op, lhs_eval_var, rhs_expr_id, bin_op_expr_span)
}
Value::String(_) => {
// Strings are a special case that we always treat as empty string during partial evaluation,
// but we still need to evaluate the RHS expression in case it contains side effects.
let rhs_control_flow = self.try_eval_expr(rhs_expr_id)?;
let EvalControlFlow::Continue(rhs_value) = rhs_control_flow else {
return Err(Error::Unexpected(
"embedded return in RHS expression".to_string(),
self.get_expr_package_span(rhs_expr_id),
));
};
Ok(EvalControlFlow::Continue(rhs_value))
}
_ => Err(Error::Unexpected(
format!("unsupported LHS value: {lhs_value}"),
lhs_span,
)),
}
}
fn eval_bin_op_with_lhs_array_operand(
&mut self,
bin_op: BinOp,
lhs_array: &Rc<Vec<Value>>,
rhs_expr_id: ExprId,
bin_op_expr_span: PackageSpan, // For diagnostic purposes only.
) -> Result<EvalControlFlow, Error> {
// Check that the binary operation is currently supported.
if matches!(bin_op, BinOp::Eq | BinOp::Neq) {
return Err(Error::Unimplemented(
"array comparison".to_string(),
bin_op_expr_span,
));
}
// The only possible binary operation with array operands at this point is addition.
assert!(
matches!(bin_op, BinOp::Add),
"expected array addition operation, got {bin_op:?}"
);
// Try to evaluate the RHS array expression to get its value.
let rhs_control_flow = self.try_eval_expr(rhs_expr_id)?;
let EvalControlFlow::Continue(rhs_value) = rhs_control_flow else {
return Err(Error::Unexpected(
"embedded return in RHS expression".to_string(),
self.get_expr_package_span(rhs_expr_id),
));
};
let Value::Array(rhs_array) = rhs_value else {
panic!("expected array value from RHS expression");
};
// Concatenate the arrays.
let concatenated_array: Vec<Value> =
lhs_array.iter().chain(rhs_array.iter()).cloned().collect();
let array_value = Value::Array(concatenated_array.into());
Ok(EvalControlFlow::Continue(array_value))
}
fn eval_bin_op_with_lhs_result_operand(
&mut self,
bin_op: BinOp,
lhs_result: val::Result,
rhs_expr_id: ExprId,
bin_op_expr_span: PackageSpan, // For diagnostic purposes only.
) -> Result<EvalControlFlow, Error> {
let rhs_control_flow = self.try_eval_expr(rhs_expr_id)?;
let EvalControlFlow::Continue(rhs_value) = rhs_control_flow else {
return Err(Error::Unexpected(
"embedded return in RHS expression".to_string(),
self.get_expr_package_span(rhs_expr_id),
));
};
let Value::Result(rhs_result) = rhs_value else {
panic!("expected result value from RHS expression");
};
// Even though to get to this path, an expression would have to be categorized as hybrid by RCA, it is
// possible that the expression is in fact purely classical.
// This can happen in cases where a data structure such an array, tuple or UDT contains a mix of static and
// dynamic values. In such instances, RCA identifies all the contents of the data structure as dynamic even if
// some values are static.
// Here we handle this case and if both operands are purely classical we evaluate them.
if let (val::Result::Val(lhs_result_value), val::Result::Val(rhs_result_value)) =
(lhs_result, rhs_result)
{
let bool_value = match bin_op {
BinOp::Eq => lhs_result_value == rhs_result_value,
BinOp::Neq => lhs_result_value != rhs_result_value,
_ => {
return Err(Error::Unexpected(
format!("invalid binary operator for Result operands: {bin_op:?})"),
bin_op_expr_span,
));
}
};
return Ok(EvalControlFlow::Continue(Value::Bool(bool_value)));
}
// Get the operands to use when generating the binary operation instruction.
let lhs_operand = self.eval_result_as_bool_operand(lhs_result);
let rhs_operand = self.eval_result_as_bool_operand(rhs_result);
// Create a variable to store the result of the expression.
let variable_id = self.resource_manager.next_var();
let rir_variable = rir::Variable {
variable_id,
ty: rir::Ty::Prim(rir::Prim::Boolean), // Binary operations between results are always Boolean.
};
// Create the binary operation instruction and add it to the current block.
let condition_code = match bin_op {
BinOp::Eq => ConditionCode::Eq,
BinOp::Neq => ConditionCode::Ne,
_ => {
return Err(Error::Unexpected(
format!("invalid binary operator for Result operands: {bin_op:?})"),
bin_op_expr_span,
));
}
};
let instruction = match (bin_op, lhs_operand, rhs_operand) {
(BinOp::Eq, Operand::Literal(Literal::Bool(true)), operand)
| (BinOp::Eq, operand, Operand::Literal(Literal::Bool(true)))
| (BinOp::Neq, Operand::Literal(Literal::Bool(false)), operand)
| (BinOp::Neq, operand, Operand::Literal(Literal::Bool(false))) => {
// One of the operands is a literal so we just need a store instruction.
Instruction::Store(operand, rir_variable)
}
// Both operators are non-literals so we need the comparison instruction.
_ => Instruction::Icmp(condition_code, lhs_operand, rhs_operand, rir_variable),
};
self.get_current_rir_block_mut().0.push(instruction);
// Return the variable as a value.
let value = Value::Var(map_rir_var_to_eval_var(rir_variable).map_err(|()| {
Error::Unexpected(
format!("{} type in binop", rir_variable.ty),
bin_op_expr_span,
)
})?);
Ok(EvalControlFlow::Continue(value))
}
fn eval_bin_op_with_lhs_classical_bool_operand(
&mut self,
bin_op: BinOp,
lhs_bool: bool,
rhs_expr_id: ExprId,
) -> Result<EvalControlFlow, Error> {
let value = match (bin_op, lhs_bool) {
// Handle short-circuiting for logical AND and logical OR.
(BinOp::AndL, false) => Value::Bool(false),
(BinOp::OrL, true) => Value::Bool(true),
// Cases for which just returning the RHS value is sufficient.
(BinOp::AndL | BinOp::Eq, true) | (BinOp::OrL | BinOp::Neq, false) => {
// Try to evaluate the RHS expression to get its value.
let rhs_control_flow = self.try_eval_expr(rhs_expr_id)?;
let EvalControlFlow::Continue(rhs_value) = rhs_control_flow else {
return Err(Error::Unexpected(
"embedded return in RHS expression".to_string(),
self.get_expr_package_span(rhs_expr_id),
));
};
rhs_value
}
// The other possible cases.
(BinOp::Eq | BinOp::Neq, _) => {
// Try to evaluate the RHS expression to get its value.
let rhs_control_flow = self.try_eval_expr(rhs_expr_id)?;
let EvalControlFlow::Continue(rhs_value) = rhs_control_flow else {
return Err(Error::Unexpected(
"embedded return in RHS expression".to_string(),
self.get_expr_package_span(rhs_expr_id),
));
};
// Create the operands.
let lhs_operand = Operand::Literal(Literal::Bool(lhs_bool));
let rhs_operand = self.map_eval_value_to_rir_operand(&rhs_value);
// If both operands are literals, evaluate the binary operation and return its value.
if let (Operand::Literal(lhs_literal), Operand::Literal(rhs_literal)) =
(lhs_operand, rhs_operand)
{
let value = eval_bin_op_with_bool_literals(bin_op, lhs_literal, rhs_literal);
return Ok(EvalControlFlow::Continue(value));
}
// Generate the specific instruction depending on the operand.
let bin_op_variable_id = self.resource_manager.next_var();
let bin_op_rir_variable = rir::Variable {
variable_id: bin_op_variable_id,
ty: rir::Ty::Prim(rir::Prim::Boolean),
};
let bin_op_ins = match bin_op {
BinOp::AndL => {
Instruction::LogicalAnd(lhs_operand, rhs_operand, bin_op_rir_variable)
}
BinOp::OrL => {
Instruction::LogicalOr(lhs_operand, rhs_operand, bin_op_rir_variable)
}
BinOp::Eq => Instruction::Icmp(
ConditionCode::Eq,
lhs_operand,
rhs_operand,
bin_op_rir_variable,
),
BinOp::Neq => Instruction::Icmp(
ConditionCode::Ne,
lhs_operand,
rhs_operand,
bin_op_rir_variable,
),
_ => panic!("unsupported binary operation for bools: {bin_op:?}"),
};
self.get_current_rir_block_mut().0.push(bin_op_ins);
Value::Var(map_rir_var_to_eval_var(bin_op_rir_variable).map_err(|()| {
Error::Unexpected(
format!("{} type in binop", bin_op_rir_variable.ty),
self.get_expr_package_span(rhs_expr_id),
)
})?)
}
_ => panic!("unsupported binary operation for bools: {bin_op:?}"),
};
Ok(EvalControlFlow::Continue(value))
}
fn eval_bin_op_with_lhs_dynamic_bool_operand(
&mut self,
bin_op: BinOp,
lhs_eval_var: Var,
rhs_expr_id: ExprId,
) -> Result<EvalControlFlow, Error> {
let result_var = match bin_op {
BinOp::Eq | BinOp::Neq => {
self.eval_comparison_bool_bin_op(bin_op, lhs_eval_var, rhs_expr_id)?
}
BinOp::AndL => {
// Logical AND Boolean operations short-circuit on false.
let lhs_rir_var = map_eval_var_to_rir_var(lhs_eval_var);
self.eval_logical_bool_bin_op(false, lhs_rir_var, rhs_expr_id)?
}
BinOp::OrL => {
// Logical OR Boolean operations short-circuit on true.
let lhs_rir_var = map_eval_var_to_rir_var(lhs_eval_var);
self.eval_logical_bool_bin_op(true, lhs_rir_var, rhs_expr_id)?
}
_ => panic!("invalid Boolean operator {bin_op:?}"),
};
Ok(EvalControlFlow::Continue(Value::Var(result_var)))
}
fn eval_comparison_bool_bin_op(
&mut self,
bin_op: BinOp,
lhs_eval_var: Var,
rhs_expr_id: ExprId,
) -> Result<Var, Error> {
// Try to evaluate the RHS expression to get its value and create a RHS operand.
let rhs_control_flow = self.try_eval_expr(rhs_expr_id)?;
let EvalControlFlow::Continue(rhs_value) = rhs_control_flow else {
return Err(Error::Unexpected(
"embedded return in RHS expression".to_string(),
self.get_expr_package_span(rhs_expr_id),
));
};
let rhs_operand = self.map_eval_value_to_rir_operand(&rhs_value);
// Get the comparison result depending on the operator and the RHS value.
let result_var = match (bin_op, rhs_operand) {
// If the RHS value is a literal, depending on the operand, the result of the Boolean comparison is just the
// LHS value.
(BinOp::Neq, Operand::Literal(Literal::Bool(false)))
| (BinOp::Eq, Operand::Literal(Literal::Bool(true))) => lhs_eval_var,
// In other cases we have to actually generate the comparison instruction.
(BinOp::Eq | BinOp::Neq, _) => {
let rir_variable = rir::Variable::new_boolean(self.resource_manager.next_var());
let lhs_operand = Operand::Variable(map_eval_var_to_rir_var(lhs_eval_var));
let condition_code = match bin_op {
BinOp::Eq => ConditionCode::Eq,
BinOp::Neq => ConditionCode::Ne,
_ => panic!("invalid Boolean comparison operator {bin_op:?}"),
};
let cmp_inst =
Instruction::Icmp(condition_code, lhs_operand, rhs_operand, rir_variable);
self.get_current_rir_block_mut().0.push(cmp_inst);
map_rir_var_to_eval_var(rir_variable).map_err(|()| {
Error::Unexpected(
format!("{} type in comparison binop", rir_variable.ty),
self.get_expr_package_span(rhs_expr_id),
)
})?
}
(_, _) => panic!("invalid Boolean comparison operator {bin_op:?}"),
};
Ok(result_var)
}
fn eval_logical_bool_bin_op(
&mut self,
short_circuit_on_true: bool,
lhs_rir_var: rir::Variable,
rhs_expr_id: ExprId,
) -> Result<Var, Error> {
// Create the variable where we will store the result of the Boolean operation and store a default value in it,
// which will only be changed inside the conditional block where the RHS expression is evaluated.
let result_var_id = self.resource_manager.next_var();
let result_rir_var = rir::Variable {
variable_id: result_var_id,
ty: rir::Ty::Prim(rir::Prim::Boolean),
};
let init_var_ins = Instruction::Store(
Operand::Literal(Literal::Bool(short_circuit_on_true)),
result_rir_var,
);
self.get_current_rir_block_mut().0.push(init_var_ins);
// Pop the current block and insert the continuation block.
let current_block_node = self.eval_context.pop_block_node();
let continuation_block_id = self.create_program_block();
let continuation_block_node = BlockNode {
id: continuation_block_id,
successor: current_block_node.successor,
};
self.eval_context.push_block_node(continuation_block_node);
// Now insert the conditional block.
let rhs_eval_block_id = self.create_program_block();
let rhs_eval_block_node = BlockNode {
id: rhs_eval_block_id,
successor: Some(continuation_block_id),
};
self.eval_context.push_block_node(rhs_eval_block_node);
// Evaluate the RHS expression
let rhs_control_flow = self.try_eval_expr(rhs_expr_id)?;
let EvalControlFlow::Continue(rhs_value) = rhs_control_flow else {
return Err(Error::Unexpected(
"embedded return in RHS expression".to_string(),
self.get_expr_package_span(rhs_expr_id),
));
};
let rhs_operand = self.map_eval_value_to_rir_operand(&rhs_value);
// Store the RHS value into the the variable that represents the result of the Boolean operation.
let store_ins = Instruction::Store(rhs_operand, result_rir_var);
self.get_current_rir_block_mut().0.push(store_ins);
let jump_ins = Instruction::Jump(continuation_block_id);
self.get_current_rir_block_mut().0.push(jump_ins);
let _ = self.eval_context.pop_block_node();
// Now that we have constructed both the conditional and continuation blocks, insert the jump instruction and
// return the variable that stores the result of the Boolean operation.
// The branching blocks depend on whether we short-circuit on true or false.
let (true_block_id, false_block_id) = if short_circuit_on_true {
(continuation_block_id, rhs_eval_block_id)
} else {
(rhs_eval_block_id, continuation_block_id)
};
let branch_metadata = self.metadata_from_expr(rhs_expr_id);