forked from carbon-language/carbon-lang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterpreter.cpp
2637 lines (2525 loc) · 109 KB
/
interpreter.cpp
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
// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "explorer/interpreter/interpreter.h"
#include <iterator>
#include <limits>
#include <map>
#include <memory>
#include <optional>
#include <random>
#include <utility>
#include <vector>
#include "common/check.h"
#include "common/error.h"
#include "explorer/ast/address.h"
#include "explorer/ast/declaration.h"
#include "explorer/ast/element.h"
#include "explorer/ast/expression.h"
#include "explorer/ast/expression_category.h"
#include "explorer/ast/value.h"
#include "explorer/base/arena.h"
#include "explorer/base/error_builders.h"
#include "explorer/base/print_as_id.h"
#include "explorer/base/source_location.h"
#include "explorer/base/trace_stream.h"
#include "explorer/interpreter/action.h"
#include "explorer/interpreter/action_stack.h"
#include "explorer/interpreter/heap.h"
#include "explorer/interpreter/pattern_match.h"
#include "explorer/interpreter/type_utils.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/raw_ostream.h"
using llvm::cast;
using llvm::dyn_cast;
using llvm::isa;
namespace Carbon {
// Limits for various overflow conditions.
static constexpr int64_t MaxTodoSize = 1e3;
static constexpr int64_t MaxStepsTaken = 1e6;
static constexpr int64_t MaxArenaAllocated = 1e9;
// Constructs an ActionStack suitable for the specified phase.
static auto MakeTodo(Phase phase, Nonnull<Heap*> heap,
Nonnull<TraceStream*> trace_stream) -> ActionStack {
switch (phase) {
case Phase::CompileTime:
return ActionStack(trace_stream);
case Phase::RunTime:
return ActionStack(trace_stream, heap);
}
}
// An Interpreter represents an instance of the Carbon abstract machine. It
// manages the state of the abstract machine, and executes the steps of Actions
// passed to it.
class Interpreter {
public:
// Constructs an Interpreter which allocates values on `arena`, and prints
// traces if `trace` is true. `phase` indicates whether it executes at
// compile time or run time.
Interpreter(Phase phase, Nonnull<Arena*> arena,
Nonnull<TraceStream*> trace_stream,
Nonnull<llvm::raw_ostream*> print_stream)
: arena_(arena),
heap_(trace_stream, arena),
todo_(MakeTodo(phase, &heap_, trace_stream)),
trace_stream_(trace_stream),
print_stream_(print_stream),
phase_(phase) {}
// Runs all the steps of `action`.
// It's not safe to call `RunAllSteps()` or `result()` after an error.
auto RunAllSteps(std::unique_ptr<Action> action) -> ErrorOr<Success>;
// The result produced by the `action` argument of the most recent
// RunAllSteps call. Cannot be called if `action` was an action that doesn't
// produce results.
auto result() const -> Nonnull<const Value*> { return todo_.result(); }
private:
auto Step() -> ErrorOr<Success>;
// State transitions for expressions value generation.
auto StepValueExp() -> ErrorOr<Success>;
// State transitions for expressions.
auto StepExp() -> ErrorOr<Success>;
// State transitions for lvalues.
auto StepLocation() -> ErrorOr<Success>;
// State transitions for witnesses.
auto StepWitness() -> ErrorOr<Success>;
// State transition for statements.
auto StepStmt() -> ErrorOr<Success>;
// State transition for declarations.
auto StepDeclaration() -> ErrorOr<Success>;
// State transition for object destruction.
auto StepCleanUp() -> ErrorOr<Success>;
auto StepDestroy() -> ErrorOr<Success>;
// State transition for type instantiation.
auto StepInstantiateType() -> ErrorOr<Success>;
auto CreateStruct(const std::vector<FieldInitializer>& fields,
const std::vector<Nonnull<const Value*>>& values)
-> Nonnull<const Value*>;
auto EvalPrim(Operator op, Nonnull<const Value*> static_type,
const std::vector<Nonnull<const Value*>>& args,
SourceLocation source_loc) -> ErrorOr<Nonnull<const Value*>>;
// Returns the result of converting `value` to type `destination_type`.
auto Convert(Nonnull<const Value*> value,
Nonnull<const Value*> destination_type,
SourceLocation source_loc) -> ErrorOr<Nonnull<const Value*>>;
// Create a class value and its base class(es) from an init struct.
auto ConvertStructToClass(Nonnull<const StructValue*> init,
Nonnull<const NominalClassType*> class_type,
SourceLocation source_loc)
-> ErrorOr<Nonnull<const NominalClassValue*>>;
// Evaluate an expression immediately, recursively, and return its result.
//
// TODO: Stop using this.
auto EvalRecursively(std::unique_ptr<Action> action)
-> ErrorOr<Nonnull<const Value*>>;
// Evaluate an associated constant by evaluating its witness and looking
// inside the impl for the corresponding value.
//
// TODO: This approach doesn't provide values that are known because they
// appear in constraints:
//
// interface Iface { let N:! i32; }
// fn PickType(N: i32) -> type { return i32; }
// fn F[T:! Iface where .N == 5](x: T) {
// var x: PickType(T.N) = 0;
// }
//
// ... will fail because we can't resolve T.N to 5 at compile time.
auto EvalAssociatedConstant(Nonnull<const AssociatedConstant*> assoc,
SourceLocation source_loc)
-> ErrorOr<Nonnull<const Value*>>;
// Instantiate a type by replacing all type variables that occur inside the
// type by the current values of those variables.
//
// For example, suppose T=i32 and U=bool. Then
// __Fn (Point(T)) -> Point(U)
// becomes
// __Fn (Point(i32)) -> Point(bool)
//
// TODO: This should be an Action.
auto InstantiateType(Nonnull<const Value*> type, SourceLocation source_loc)
-> ErrorOr<Nonnull<const Value*>>;
// Instantiate a set of bindings by replacing all type variables that occur
// within it by the current values of those variables.
auto InstantiateBindings(Nonnull<const Bindings*> bindings,
SourceLocation source_loc)
-> ErrorOr<Nonnull<const Bindings*>>;
// Instantiate a witness by replacing all type variables and impl binding
// references that occur within it by the current values of those variables.
auto InstantiateWitness(Nonnull<const Witness*> witness,
SourceLocation source_loc)
-> ErrorOr<Nonnull<const Witness*>>;
// Call the function `fun` with the given `arg` and the `witnesses`
// for the function's impl bindings.
auto CallFunction(const CallExpression& call, Nonnull<const Value*> fun,
Nonnull<const Value*> arg, ImplWitnessMap&& witnesses,
std::optional<AllocationId> location_received)
-> ErrorOr<Success>;
// Call the destructor method in `fun`, with any self argument bound to
// `receiver`.
auto CallDestructor(Nonnull<const DestructorDeclaration*> fun,
ExpressionResult receiver) -> ErrorOr<Success>;
// If the given method or destructor `decl` has a self argument, bind it to
// `receiver`.
void BindSelfIfPresent(Nonnull<const CallableDeclaration*> decl,
ExpressionResult receiver, RuntimeScope& method_scope,
BindingMap& generic_args,
const SourceLocation& source_location);
auto phase() const -> Phase { return phase_; }
Nonnull<Arena*> arena_;
Heap heap_;
ActionStack todo_;
Nonnull<TraceStream*> trace_stream_;
// The stream for the Print intrinsic.
Nonnull<llvm::raw_ostream*> print_stream_;
Phase phase_;
// The number of steps taken by the interpreter. Used for infinite loop
// detection.
int64_t steps_taken_ = 0;
};
//
// State Operations
//
auto Interpreter::EvalPrim(Operator op, Nonnull<const Value*> /*static_type*/,
const std::vector<Nonnull<const Value*>>& args,
SourceLocation source_loc)
-> ErrorOr<Nonnull<const Value*>> {
switch (op) {
case Operator::Neg:
case Operator::Add:
case Operator::Sub:
case Operator::Div:
case Operator::Mul: {
llvm::APInt op0(64, cast<IntValue>(*args[0]).value());
llvm::APInt result;
if (op == Operator::Neg) {
result = -op0;
} else {
llvm::APInt op1(64, cast<IntValue>(*args[1]).value());
if (op == Operator::Add) {
result = op0 + op1;
} else if (op == Operator::Sub) {
result = op0 - op1;
} else if (op == Operator::Mul) {
result = op0 * op1;
} else if (op == Operator::Div) {
if (op1.getSExtValue() == 0) {
return ProgramError(source_loc) << "division by zero";
}
result = op0.sdiv(op1);
}
}
if (result.isSignedIntN(32)) {
return arena_->New<IntValue>(result.getSExtValue());
} else {
return ProgramError(source_loc) << "integer overflow";
}
}
case Operator::Mod: {
const auto& lhs = cast<IntValue>(*args[0]).value();
const auto& rhs = cast<IntValue>(*args[1]).value();
if (rhs == 0) {
return ProgramError(source_loc) << "division by zero";
}
return arena_->New<IntValue>(lhs % rhs);
}
case Operator::Not:
return arena_->New<BoolValue>(!cast<BoolValue>(*args[0]).value());
case Operator::And:
return arena_->New<BoolValue>(cast<BoolValue>(*args[0]).value() &&
cast<BoolValue>(*args[1]).value());
case Operator::Or:
return arena_->New<BoolValue>(cast<BoolValue>(*args[0]).value() ||
cast<BoolValue>(*args[1]).value());
case Operator::Ptr:
return arena_->New<PointerType>(args[0]);
case Operator::Deref: {
CARBON_ASSIGN_OR_RETURN(
const auto* value,
heap_.Read(cast<PointerValue>(*args[0]).address(), source_loc));
return arena_->New<ReferenceExpressionValue>(
value, cast<PointerValue>(*args[0]).address());
}
case Operator::AddressOf:
return arena_->New<PointerValue>(cast<LocationValue>(*args[0]).address());
case Operator::As:
case Operator::Eq:
case Operator::NotEq:
case Operator::Less:
case Operator::LessEq:
case Operator::Greater:
case Operator::GreaterEq:
case Operator::BitwiseAnd:
case Operator::BitwiseOr:
case Operator::BitwiseXor:
case Operator::BitShiftLeft:
case Operator::BitShiftRight:
case Operator::Complement:
CARBON_FATAL("operator {0} should always be rewritten",
OperatorToString(op));
}
}
auto Interpreter::CreateStruct(const std::vector<FieldInitializer>& fields,
const std::vector<Nonnull<const Value*>>& values)
-> Nonnull<const Value*> {
std::vector<NamedValue> elements;
for (const auto [field, value] : llvm::zip_equal(fields, values)) {
elements.push_back({field.name(), value});
}
return arena_->New<StructValue>(std::move(elements));
}
auto Interpreter::StepLocation() -> ErrorOr<Success> {
Action& act = todo_.CurrentAction();
const Expression& exp = cast<LocationAction>(act).expression();
switch (exp.kind()) {
case ExpressionKind::IdentifierExpression: {
// { {x :: C, E, F} :: S, H}
// -> { {E(x) :: C, E, F} :: S, H}
CARBON_ASSIGN_OR_RETURN(
Nonnull<const Value*> value,
todo_.ValueOfNode(cast<IdentifierExpression>(exp).value_node(),
exp.source_loc()));
CARBON_CHECK(isa<LocationValue>(value), "{0}", *value);
return todo_.FinishAction(value);
}
case ExpressionKind::SimpleMemberAccessExpression: {
const auto& access = cast<SimpleMemberAccessExpression>(exp);
const auto constant_value = access.constant_value();
if (auto rewrite = access.rewritten_form()) {
return todo_.ReplaceWith(std::make_unique<LocationAction>(*rewrite));
}
if (act.pos() == 0) {
// { {e.f :: C, E, F} :: S, H}
// -> { e :: [].f :: C, E, F} :: S, H}
return todo_.Spawn(std::make_unique<LocationAction>(&access.object()));
} else if (act.pos() == 1 && constant_value) {
return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
*constant_value, access.source_loc()));
} else {
if (constant_value) {
return todo_.FinishAction(act.results().back());
} else {
// { v :: [].f :: C, E, F} :: S, H}
// -> { { &v.f :: C, E, F} :: S, H }
Address object = cast<LocationValue>(*act.results()[0]).address();
Address member = object.ElementAddress(&access.member());
return todo_.FinishAction(arena_->New<LocationValue>(member));
}
}
}
case ExpressionKind::CompoundMemberAccessExpression: {
const auto& access = cast<CompoundMemberAccessExpression>(exp);
const auto constant_value = access.constant_value();
if (act.pos() == 0) {
return todo_.Spawn(std::make_unique<LocationAction>(&access.object()));
}
if (act.pos() == 1 && constant_value) {
return todo_.Spawn(std::make_unique<TypeInstantiationAction>(
*constant_value, access.source_loc()));
} else {
if (constant_value) {
return todo_.FinishAction(act.results().back());
}
CARBON_CHECK(!access.member().interface().has_value(),
"unexpected location interface member");
CARBON_ASSIGN_OR_RETURN(
Nonnull<const Value*> val,
Convert(act.results()[0], *access.member().base_type(),
exp.source_loc()));
Address object = cast<LocationValue>(*val).address();
Address field = object.ElementAddress(&access.member().member());
return todo_.FinishAction(arena_->New<LocationValue>(field));
}
}
case ExpressionKind::BaseAccessExpression: {
const auto& access = cast<BaseAccessExpression>(exp);
if (act.pos() == 0) {
// Get LocationValue for expression.
return todo_.Spawn(std::make_unique<LocationAction>(&access.object()));
} else {
// Append `.base` element to the address, and return the new
// LocationValue.
Address object = cast<LocationValue>(*act.results()[0]).address();
Address base = object.ElementAddress(&access.element());
return todo_.FinishAction(arena_->New<LocationValue>(base));
}
}
case ExpressionKind::IndexExpression: {
if (act.pos() == 0) {
// { {e[i] :: C, E, F} :: S, H}
// -> { e :: [][i] :: C, E, F} :: S, H}
return todo_.Spawn(std::make_unique<LocationAction>(
&cast<IndexExpression>(exp).object()));
} else if (act.pos() == 1) {
return todo_.Spawn(std::make_unique<ValueExpressionAction>(
&cast<IndexExpression>(exp).offset()));
} else {
// { v :: [][i] :: C, E, F} :: S, H}
// -> { { &v[i] :: C, E, F} :: S, H }
Address object = cast<LocationValue>(*act.results()[0]).address();
const auto index = cast<IntValue>(*act.results()[1]).value();
Address field = object.ElementAddress(
arena_->New<PositionalElement>(index, &exp.static_type()));
return todo_.FinishAction(arena_->New<LocationValue>(field));
}
}
case ExpressionKind::OperatorExpression: {
const auto& op = cast<OperatorExpression>(exp);
if (auto rewrite = op.rewritten_form()) {
return todo_.ReplaceWith(std::make_unique<LocationAction>(*rewrite));
}
if (op.op() != Operator::Deref) {
CARBON_FATAL(
"Can't treat primitive operator expression as location: {0}", exp);
}
if (act.pos() == 0) {
return todo_.Spawn(
std::make_unique<ValueExpressionAction>(op.arguments()[0]));
} else {
const auto& res = cast<PointerValue>(*act.results()[0]);
return todo_.FinishAction(arena_->New<LocationValue>(res.address()));
}
break;
}
case ExpressionKind::TupleLiteral:
case ExpressionKind::StructLiteral:
case ExpressionKind::StructTypeLiteral:
case ExpressionKind::IntLiteral:
case ExpressionKind::BoolLiteral:
case ExpressionKind::CallExpression:
case ExpressionKind::IntTypeLiteral:
case ExpressionKind::BoolTypeLiteral:
case ExpressionKind::TypeTypeLiteral:
case ExpressionKind::FunctionTypeLiteral:
case ExpressionKind::StringLiteral:
case ExpressionKind::StringTypeLiteral:
case ExpressionKind::ValueLiteral:
case ExpressionKind::IntrinsicExpression:
case ExpressionKind::IfExpression:
case ExpressionKind::WhereExpression:
case ExpressionKind::DotSelfExpression:
case ExpressionKind::ArrayTypeLiteral:
case ExpressionKind::BuiltinConvertExpression:
CARBON_FATAL("Can't treat expression as location: {0}", exp);
case ExpressionKind::UnimplementedExpression:
CARBON_FATAL("Unimplemented: {0}", exp);
}
}
auto Interpreter::EvalRecursively(std::unique_ptr<Action> action)
-> ErrorOr<Nonnull<const Value*>> {
todo_.BeginRecursiveAction();
CARBON_RETURN_IF_ERROR(todo_.Spawn(std::move(action)));
// Note that the only `RecursiveAction` we can encounter here is our own --
// if a nested action begins a recursive action, it will run until that
// action is finished and popped off the queue before returning to us.
while (!isa<RecursiveAction>(todo_.CurrentAction())) {
CARBON_RETURN_IF_ERROR(Step());
}
if (trace_stream_->is_enabled()) {
trace_stream_->End() << "recursive eval done\n";
}
Nonnull<const Value*> result =
cast<RecursiveAction>(todo_.CurrentAction()).results()[0];
CARBON_RETURN_IF_ERROR(todo_.FinishAction());
return result;
}
auto Interpreter::EvalAssociatedConstant(
Nonnull<const AssociatedConstant*> assoc, SourceLocation source_loc)
-> ErrorOr<Nonnull<const Value*>> {
// Instantiate the associated constant.
CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> interface,
InstantiateType(&assoc->interface(), source_loc));
CARBON_ASSIGN_OR_RETURN(Nonnull<const Witness*> witness,
InstantiateWitness(&assoc->witness(), source_loc));
const auto* impl_witness = dyn_cast<ImplWitness>(witness);
if (!impl_witness) {
CARBON_CHECK(phase() == Phase::CompileTime,
"symbolic witnesses should only be formed at compile time");
CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> base,
InstantiateType(&assoc->base(), source_loc));
return arena_->New<AssociatedConstant>(base, cast<InterfaceType>(interface),
&assoc->constant(), witness);
}
// We have an impl. Extract the value from it.
Nonnull<const ConstraintType*> constraint =
impl_witness->declaration().constraint_type();
std::optional<Nonnull<const Value*>> result;
for (const auto& rewrite : constraint->rewrite_constraints()) {
if (&rewrite.constant->constant() == &assoc->constant() &&
TypeEqual(&rewrite.constant->interface(), interface, std::nullopt)) {
// TODO: The value might depend on the parameters of the impl. We need to
// substitute impl_witness->type_args() into the value.
result = rewrite.converted_replacement;
break;
}
}
if (!result) {
CARBON_FATAL(
"{0} with constraint {1} is missing value for associated constant "
"{2}.{3}",
impl_witness->declaration(), *constraint, *interface,
assoc->constant().binding().name());
}
return *result;
}
auto Interpreter::InstantiateType(Nonnull<const Value*> type,
SourceLocation source_loc)
-> ErrorOr<Nonnull<const Value*>> {
if (trace_stream_->is_enabled()) {
trace_stream_->Start() << "instantiating type `" << *type << "` ("
<< source_loc << ")\n";
}
const Value* value = nullptr;
switch (type->kind()) {
case Value::Kind::VariableType: {
CARBON_ASSIGN_OR_RETURN(
value,
todo_.ValueOfNode(&cast<VariableType>(*type).binding(), source_loc));
if (const auto* location = dyn_cast<LocationValue>(value)) {
CARBON_ASSIGN_OR_RETURN(value,
heap_.Read(location->address(), source_loc));
}
break;
}
case Value::Kind::InterfaceType: {
const auto& interface_type = cast<InterfaceType>(*type);
CARBON_ASSIGN_OR_RETURN(
Nonnull<const Bindings*> bindings,
InstantiateBindings(&interface_type.bindings(), source_loc));
value =
arena_->New<InterfaceType>(&interface_type.declaration(), bindings);
break;
}
case Value::Kind::NamedConstraintType: {
const auto& constraint_type = cast<NamedConstraintType>(*type);
CARBON_ASSIGN_OR_RETURN(
Nonnull<const Bindings*> bindings,
InstantiateBindings(&constraint_type.bindings(), source_loc));
value = arena_->New<NamedConstraintType>(&constraint_type.declaration(),
bindings);
break;
}
case Value::Kind::ChoiceType: {
const auto& choice_type = cast<ChoiceType>(*type);
CARBON_ASSIGN_OR_RETURN(
Nonnull<const Bindings*> bindings,
InstantiateBindings(&choice_type.bindings(), source_loc));
value = arena_->New<ChoiceType>(&choice_type.declaration(), bindings);
break;
}
case Value::Kind::AssociatedConstant: {
CARBON_ASSIGN_OR_RETURN(
Nonnull<const Value*> type_value,
EvalAssociatedConstant(cast<AssociatedConstant>(type), source_loc));
value = type_value;
break;
}
default:
value = type;
break;
}
if (trace_stream_->is_enabled()) {
trace_stream_->End() << "instantiated type `" << *type << "` as `" << *value
<< "` (" << source_loc << ")\n";
}
return value;
}
auto Interpreter::InstantiateBindings(Nonnull<const Bindings*> bindings,
SourceLocation source_loc)
-> ErrorOr<Nonnull<const Bindings*>> {
BindingMap args = bindings->args();
for (auto& [var, arg] : args) {
CARBON_ASSIGN_OR_RETURN(arg, InstantiateType(arg, source_loc));
}
ImplWitnessMap witnesses = bindings->witnesses();
for (auto& [bind, witness] : witnesses) {
CARBON_ASSIGN_OR_RETURN(
witness, InstantiateWitness(cast<Witness>(witness), source_loc));
}
if (args == bindings->args() && witnesses == bindings->witnesses()) {
return bindings;
}
return arena_->New<Bindings>(std::move(args), std::move(witnesses));
}
auto Interpreter::InstantiateWitness(Nonnull<const Witness*> witness,
SourceLocation source_loc)
-> ErrorOr<Nonnull<const Witness*>> {
CARBON_ASSIGN_OR_RETURN(
Nonnull<const Value*> value,
EvalRecursively(std::make_unique<WitnessAction>(witness, source_loc)));
return cast<Witness>(value);
}
auto Interpreter::ConvertStructToClass(
Nonnull<const StructValue*> init_struct,
Nonnull<const NominalClassType*> class_type, SourceLocation source_loc)
-> ErrorOr<Nonnull<const NominalClassValue*>> {
std::vector<NamedValue> struct_values;
std::optional<Nonnull<const NominalClassValue*>> base_instance;
// Instantiate the `destination_type` to obtain the runtime
// type of the object.
CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> inst_class,
InstantiateType(class_type, source_loc));
for (const auto& field : init_struct->elements()) {
if (field.name == NominalClassValue::BaseField) {
CARBON_CHECK(class_type->base().has_value(),
"Invalid 'base' field for class '{0}' without base class.",
class_type->declaration().name());
CARBON_ASSIGN_OR_RETURN(
auto base,
Convert(field.value, class_type->base().value(), source_loc));
base_instance = cast<NominalClassValue>(base);
} else {
struct_values.push_back(field);
}
}
CARBON_CHECK(!cast<NominalClassType>(inst_class)->base() || base_instance,
"Invalid conversion for `{0}`: base class missing", *inst_class);
auto* converted_init_struct =
arena_->New<StructValue>(std::move(struct_values));
Nonnull<const NominalClassValue** const> class_value_ptr =
base_instance ? (*base_instance)->class_value_ptr()
: arena_->New<const NominalClassValue*>();
return arena_->New<NominalClassValue>(inst_class, converted_init_struct,
base_instance, class_value_ptr);
}
auto Interpreter::Convert(Nonnull<const Value*> value,
Nonnull<const Value*> destination_type,
SourceLocation source_loc)
-> ErrorOr<Nonnull<const Value*>> {
switch (value->kind()) {
case Value::Kind::IntValue:
case Value::Kind::FunctionValue:
case Value::Kind::DestructorValue:
case Value::Kind::BoundMethodValue:
case Value::Kind::LocationValue:
case Value::Kind::BoolValue:
case Value::Kind::NominalClassValue:
case Value::Kind::AlternativeValue:
case Value::Kind::UninitializedValue:
case Value::Kind::IntType:
case Value::Kind::BoolType:
case Value::Kind::TypeType:
case Value::Kind::FunctionType:
case Value::Kind::PointerType:
case Value::Kind::TupleType:
case Value::Kind::StructType:
case Value::Kind::AutoType:
case Value::Kind::NominalClassType:
case Value::Kind::MixinPseudoType:
case Value::Kind::InterfaceType:
case Value::Kind::NamedConstraintType:
case Value::Kind::ConstraintType:
case Value::Kind::ImplWitness:
case Value::Kind::BindingWitness:
case Value::Kind::ConstraintWitness:
case Value::Kind::ConstraintImplWitness:
case Value::Kind::ParameterizedEntityName:
case Value::Kind::ChoiceType:
case Value::Kind::BindingPlaceholderValue:
case Value::Kind::AddrValue:
case Value::Kind::AlternativeConstructorValue:
case Value::Kind::StringType:
case Value::Kind::StringValue:
case Value::Kind::TypeOfMixinPseudoType:
case Value::Kind::TypeOfParameterizedEntityName:
case Value::Kind::TypeOfMemberName:
case Value::Kind::TypeOfNamespaceName:
case Value::Kind::StaticArrayType:
case Value::Kind::MemberName:
// TODO: add `CARBON_CHECK(TypeEqual(type, value->dynamic_type()))`, once
// we have Value::dynamic_type.
return value;
case Value::Kind::StructValue: {
const auto& struct_val = cast<StructValue>(*value);
switch (destination_type->kind()) {
case Value::Kind::StructType: {
const auto& destination_struct_type =
cast<StructType>(*destination_type);
std::vector<NamedValue> new_elements;
for (const auto& [field_name, field_type] :
destination_struct_type.fields()) {
std::optional<Nonnull<const Value*>> old_value =
struct_val.FindField(field_name);
CARBON_ASSIGN_OR_RETURN(
Nonnull<const Value*> val,
Convert(*old_value, field_type, source_loc));
new_elements.push_back({field_name, val});
}
return arena_->New<StructValue>(std::move(new_elements));
}
case Value::Kind::NominalClassType: {
CARBON_ASSIGN_OR_RETURN(
auto class_value,
ConvertStructToClass(cast<StructValue>(value),
cast<NominalClassType>(destination_type),
source_loc));
return class_value;
}
case Value::Kind::TypeType:
case Value::Kind::ConstraintType:
case Value::Kind::NamedConstraintType:
case Value::Kind::InterfaceType: {
CARBON_CHECK(struct_val.elements().empty(),
"only empty structs convert to `type`");
return arena_->New<StructType>();
}
default: {
CARBON_CHECK(IsValueKindDependent(destination_type) ||
(isa<TypeType, ConstraintType>(destination_type)),
"Can't convert value {0} to type {1}", *value,
*destination_type);
return value;
}
}
}
case Value::Kind::TupleValue: {
const auto* tuple = cast<TupleValue>(value);
std::vector<Nonnull<const Value*>> destination_element_types;
switch (destination_type->kind()) {
case Value::Kind::TupleType:
destination_element_types =
cast<TupleType>(destination_type)->elements();
break;
case Value::Kind::StaticArrayType: {
const auto& array_type = cast<StaticArrayType>(*destination_type);
CARBON_CHECK(array_type.has_size());
destination_element_types.resize(array_type.size(),
&array_type.element_type());
break;
}
case Value::Kind::TypeType:
case Value::Kind::ConstraintType:
case Value::Kind::NamedConstraintType:
case Value::Kind::InterfaceType: {
std::vector<Nonnull<const Value*>> new_elements;
Nonnull<const Value*> type_type = arena_->New<TypeType>();
for (Nonnull<const Value*> value : tuple->elements()) {
CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> value_as_type,
Convert(value, type_type, source_loc));
new_elements.push_back(value_as_type);
}
return arena_->New<TupleType>(std::move(new_elements));
}
default: {
CARBON_CHECK(IsValueKindDependent(destination_type) ||
(isa<TypeType, ConstraintType>(destination_type)),
"Can't convert value {0} to type {1}", *value,
*destination_type);
return value;
}
}
std::vector<Nonnull<const Value*>> new_elements;
for (const auto [element, dest_type] :
llvm::zip_equal(tuple->elements(), destination_element_types)) {
CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> val,
Convert(element, dest_type, source_loc));
new_elements.push_back(val);
}
return arena_->New<TupleValue>(std::move(new_elements));
}
case Value::Kind::VariableType: {
std::optional<Nonnull<const Value*>> source_type;
// While type-checking a `where` expression, we can evaluate a reference
// to its self binding before we know its type. In this case, the self
// binding is always a type.
//
// TODO: Add a conversion kind to BuiltinConvertExpression so that we
// don't need to look at the types and reconstruct what kind of
// conversion is being performed from here.
if (cast<VariableType>(value)->binding().is_type_checked()) {
CARBON_ASSIGN_OR_RETURN(
source_type,
InstantiateType(&cast<VariableType>(value)->binding().static_type(),
source_loc));
}
if (isa<TypeType, ConstraintType, NamedConstraintType, InterfaceType>(
destination_type) &&
(!source_type ||
isa<TypeType, ConstraintType, NamedConstraintType, InterfaceType>(
*source_type))) {
// No further conversions are required.
return value;
}
// We need to convert this, and we don't know how because we don't have
// the value yet.
return ProgramError(source_loc)
<< "value of generic binding " << *value << " is not known";
}
case Value::Kind::AssociatedConstant: {
CARBON_ASSIGN_OR_RETURN(
Nonnull<const Value*> value,
EvalAssociatedConstant(cast<AssociatedConstant>(value), source_loc));
if (const auto* new_const = dyn_cast<AssociatedConstant>(value)) {
// TODO: Detect whether conversions are required in type-checking.
if (isa<TypeType, ConstraintType, NamedConstraintType, InterfaceType>(
destination_type) &&
isa<TypeType, ConstraintType, NamedConstraintType, InterfaceType>(
new_const->constant().static_type())) {
// No further conversions are required.
return value;
}
// We need to convert this, and we don't know how because we don't have
// the value yet.
return ProgramError(source_loc)
<< "value of associated constant " << *value << " is not known";
}
return Convert(value, destination_type, source_loc);
}
case Value::Kind::PointerValue: {
if (destination_type->kind() != Value::Kind::PointerType ||
cast<PointerType>(destination_type)->pointee_type().kind() !=
Value::Kind::NominalClassType) {
// No conversion needed.
return value;
}
// Get pointee value.
const auto* src_ptr = cast<PointerValue>(value);
CARBON_ASSIGN_OR_RETURN(const auto* pointee,
heap_.Read(src_ptr->address(), source_loc))
CARBON_CHECK(pointee->kind() == Value::Kind::NominalClassValue,
"Unexpected pointer type");
// Conversion logic for subtyping for function arguments only.
// TODO: Drop when able to rewrite subtyping in TypeChecker for arguments.
const auto* dest_ptr = cast<PointerType>(destination_type);
std::optional<Nonnull<const NominalClassValue*>> class_subobj =
cast<NominalClassValue>(pointee);
auto new_addr = src_ptr->address();
while (class_subobj) {
if (TypeEqual(&(*class_subobj)->type(), &dest_ptr->pointee_type(),
std::nullopt)) {
return arena_->New<PointerValue>(new_addr);
}
class_subobj = (*class_subobj)->base();
new_addr = new_addr.ElementAddress(
arena_->New<BaseElement>(&dest_ptr->pointee_type()));
}
// Unable to resolve, return as-is.
// TODO: Produce error instead once we can properly substitute
// parameterized types for pointers in function call parameters.
return value;
}
case Value::Kind::ReferenceExpressionValue: {
const auto* expr_value = cast<ReferenceExpressionValue>(value);
CARBON_ASSIGN_OR_RETURN(
Nonnull<const Value*> converted,
Convert(expr_value->value(), destination_type, source_loc));
if (converted == expr_value->value()) {
return expr_value;
} else {
return converted;
}
}
}
}
auto Interpreter::CallFunction(const CallExpression& call,
Nonnull<const Value*> fun,
Nonnull<const Value*> arg,
ImplWitnessMap&& witnesses,
std::optional<AllocationId> location_received)
-> ErrorOr<Success> {
if (trace_stream_->is_enabled()) {
trace_stream_->Call() << "calling function: " << *fun << "\n";
}
switch (fun->kind()) {
case Value::Kind::AlternativeConstructorValue: {
const auto& alt = cast<AlternativeConstructorValue>(*fun);
return todo_.FinishAction(arena_->New<AlternativeValue>(
&alt.choice(), &alt.alternative(), cast<TupleValue>(arg)));
}
case Value::Kind::FunctionValue:
case Value::Kind::BoundMethodValue: {
const auto* func_val = cast<FunctionOrMethodValue>(fun);
const FunctionDeclaration& function = func_val->declaration();
if (!function.body().has_value()) {
return ProgramError(call.source_loc())
<< "attempt to call function `" << function.name()
<< "` that has not been defined";
}
if (!function.is_type_checked()) {
return ProgramError(call.source_loc())
<< "attempt to call function `" << function.name()
<< "` that has not been fully type-checked";
}
// Enter the binding scope to make any deduced arguments visible before
// we resolve the self type and parameter type.
auto& binding_scope = todo_.CurrentAction().scope().value();
// Bring the deduced arguments and their witnesses into scope.
for (const auto& [bind, val] : call.deduced_args()) {
CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> inst_val,
InstantiateType(val, call.source_loc()));
binding_scope.BindValue(bind->original(), inst_val);
}
for (const auto& [impl_bind, witness] : witnesses) {
binding_scope.BindValue(impl_bind->original(), witness);
}
// Bring the arguments that are determined by the function value into
// scope. This includes the arguments for the class of which the function
// is a member.
for (const auto& [bind, val] : func_val->type_args()) {
binding_scope.BindValue(bind->original(), val);
}
for (const auto& [impl_bind, witness] : func_val->witnesses()) {
binding_scope.BindValue(impl_bind->original(), witness);
}
RuntimeScope function_scope(&heap_);
BindingMap generic_args;
// Bind the receiver to the `self` parameter, if there is one.
if (const auto* method_val = dyn_cast<BoundMethodValue>(func_val)) {
BindSelfIfPresent(&function,
ExpressionResult::Value(method_val->receiver()),
function_scope, generic_args, call.source_loc());
}
CARBON_ASSIGN_OR_RETURN(
Nonnull<const Value*> converted_args,
Convert(arg, &function.param_pattern().static_type(),
call.source_loc()));
// Bind the arguments to the parameters.
bool success = PatternMatch(&function.param_pattern().value(),
ExpressionResult::Value(converted_args),
call.source_loc(), &function_scope,
generic_args, trace_stream_, this->arena_);
CARBON_CHECK(success, "Failed to bind arguments to parameters");
return todo_.Spawn(std::make_unique<StatementAction>(*function.body(),
location_received),
std::move(function_scope));
}
case Value::Kind::ParameterizedEntityName: {
const auto& name = cast<ParameterizedEntityName>(*fun);
const Declaration& decl = name.declaration();
RuntimeScope params_scope(&heap_);
BindingMap generic_args;
CARBON_CHECK(PatternMatch(&name.params().value(),
ExpressionResult::Value(arg), call.source_loc(),
¶ms_scope, generic_args, trace_stream_,
this->arena_));
Nonnull<const Bindings*> bindings =
arena_->New<Bindings>(std::move(generic_args), std::move(witnesses));
switch (decl.kind()) {
case DeclarationKind::ClassDeclaration: {
const auto& class_decl = cast<ClassDeclaration>(decl);
return todo_.FinishAction(arena_->New<NominalClassType>(
&class_decl, bindings, class_decl.base_type(), EmptyVTable()));
}
case DeclarationKind::InterfaceDeclaration:
return todo_.FinishAction(arena_->New<InterfaceType>(
&cast<InterfaceDeclaration>(decl), bindings));
case DeclarationKind::ConstraintDeclaration:
return todo_.FinishAction(arena_->New<NamedConstraintType>(
&cast<ConstraintDeclaration>(decl), bindings));
case DeclarationKind::ChoiceDeclaration:
return todo_.FinishAction(arena_->New<ChoiceType>(
&cast<ChoiceDeclaration>(decl), bindings));
default:
CARBON_FATAL("unknown kind of ParameterizedEntityName {0}", decl);
}
}
default:
return ProgramError(call.source_loc())
<< "in call, expected a function, not " << *fun;
}
}
auto Interpreter::CallDestructor(Nonnull<const DestructorDeclaration*> fun,
ExpressionResult receiver)
-> ErrorOr<Success> {
const DestructorDeclaration& method = *fun;
CARBON_CHECK(method.is_method());
RuntimeScope method_scope(&heap_);
BindingMap generic_args;
BindSelfIfPresent(fun, receiver, method_scope, generic_args,
SourceLocation::DiagnosticsIgnored());