forked from carbon-language/carbon-lang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
value.cpp
1370 lines (1322 loc) · 49.2 KB
/
value.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/ast/value.h"
#include <algorithm>
#include <optional>
#include <string_view>
#include "common/check.h"
#include "common/error.h"
#include "explorer/ast/declaration.h"
#include "explorer/ast/element.h"
#include "explorer/ast/element_path.h"
#include "explorer/ast/value_transform.h"
#include "explorer/base/arena.h"
#include "explorer/base/error_builders.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/Casting.h"
namespace Carbon {
using llvm::cast;
using llvm::dyn_cast;
using llvm::dyn_cast_or_null;
using llvm::isa;
namespace {
// A visitor that walks the Value*s nested within a value.
struct NestedValueVisitor {
template <typename T>
auto VisitParts(const T& decomposable) -> bool {
return decomposable.Decompose(
[&](const auto&... parts) { return (Visit(parts) && ...); });
}
auto Visit(Nonnull<const Value*> value) -> bool {
if (!callback(value)) {
return false;
}
return value->Visit<bool>(
[&](const auto* derived_value) { return VisitParts(*derived_value); });
}
auto Visit(Nonnull<const Bindings*> bindings) -> bool {
for (auto [binding, value] : bindings->args()) {
if (!Visit(value)) {
return false;
}
}
for (auto [binding, value] : bindings->witnesses()) {
if (!Visit(value)) {
return false;
}
}
return true;
}
template <typename T>
auto Visit(const std::vector<T>& vec) -> bool {
for (auto& v : vec) {
if (!Visit(v)) {
return false;
}
}
return true;
}
template <typename T>
auto Visit(const std::optional<T>& opt) -> bool {
return !opt || Visit(*opt);
}
template <typename T,
typename = std::enable_if_t<IsRecursivelyTransformable<T>>>
auto Visit(Nonnull<const T*> value) -> bool {
return VisitParts(*value);
}
template <typename T,
typename = std::enable_if_t<IsRecursivelyTransformable<T>>>
auto Visit(const T& value) -> bool {
return VisitParts(value);
}
// Other value components can't refer to a value.
auto Visit(Nonnull<const AstNode*>) -> bool { return true; }
auto Visit(ValueNodeView) -> bool { return true; }
auto Visit(int) -> bool { return true; }
auto Visit(Address) -> bool { return true; }
auto Visit(ExpressionCategory) -> bool { return true; }
auto Visit(const std::string&) -> bool { return true; }
auto Visit(Nonnull<const NominalClassValue**>) -> bool {
// This is the pointer to the most-derived value within a class value,
// which is not "within" this value, so we shouldn't visit it.
return true;
}
auto Visit(const VTable*) -> bool { return true; }
llvm::function_ref<bool(const Value*)> callback;
};
} // namespace
auto VisitNestedValues(Nonnull<const Value*> value,
llvm::function_ref<bool(const Value*)> visitor) -> bool {
return NestedValueVisitor{.callback = visitor}.Visit(value);
}
auto StructValue::FindField(std::string_view name) const
-> std::optional<Nonnull<const Value*>> {
for (const NamedValue& element : elements_) {
if (element.name == name) {
return element.value;
}
}
return std::nullopt;
}
NominalClassValue::NominalClassValue(
Nonnull<const Value*> type, Nonnull<const Value*> inits,
std::optional<Nonnull<const NominalClassValue*>> base,
Nonnull<const NominalClassValue** const> class_value_ptr)
: Value(Kind::NominalClassValue),
type_(type),
inits_(inits),
base_(base),
class_value_ptr_(class_value_ptr) {
CARBON_CHECK(!base || (*base)->class_value_ptr() == class_value_ptr);
// Update ancestors's class value to point to latest child.
*class_value_ptr_ = this;
}
static auto FindClassField(Nonnull<const NominalClassValue*> object,
std::string_view name)
-> std::optional<Nonnull<const Value*>> {
if (auto field = cast<StructValue>(object->inits()).FindField(name)) {
return field;
}
if (object->base().has_value()) {
return FindClassField(object->base().value(), name);
}
return std::nullopt;
}
static auto GetBaseElement(Nonnull<const NominalClassValue*> class_value,
SourceLocation source_loc)
-> ErrorOr<Nonnull<const Value*>> {
const auto base = cast<NominalClassValue>(class_value)->base();
if (!base.has_value()) {
return ProgramError(source_loc)
<< "Non-existent base class for " << *class_value;
}
return base.value();
}
static auto GetPositionalElement(Nonnull<const TupleValue*> tuple,
const ElementPath::Component& path_comp,
SourceLocation source_loc)
-> ErrorOr<Nonnull<const Value*>> {
CARBON_CHECK(path_comp.element()->kind() == ElementKind::PositionalElement,
"Invalid non-tuple member");
const auto* tuple_element = cast<PositionalElement>(path_comp.element());
const size_t index = tuple_element->index();
if (index < 0 || index >= tuple->elements().size()) {
return ProgramError(source_loc)
<< "index " << index << " out of range for " << *tuple;
}
return tuple->elements()[index];
}
static auto GetNamedElement(Nonnull<Arena*> arena, Nonnull<const Value*> v,
const ElementPath::Component& field,
SourceLocation source_loc,
std::optional<Nonnull<const Value*>> me_value)
-> ErrorOr<Nonnull<const Value*>> {
CARBON_CHECK(field.element()->kind() == ElementKind::NamedElement,
"Invalid element, expecting NamedElement");
const auto* member = cast<NamedElement>(field.element());
const auto f = member->name();
if (field.witness().has_value()) {
const auto* witness = cast<Witness>(*field.witness());
// Associated constants.
if (const auto* assoc_const =
dyn_cast_or_null<AssociatedConstantDeclaration>(
member->declaration().value_or(nullptr))) {
CARBON_CHECK(field.interface(), "have witness but no interface");
// TODO: Use witness to find the value of the constant.
return arena->New<AssociatedConstant>(v, *field.interface(), assoc_const,
witness);
}
// Associated functions.
if (const auto* impl_witness = dyn_cast<ImplWitness>(witness)) {
if (std::optional<Nonnull<const Declaration*>> mem_decl =
FindMember(f, impl_witness->declaration().members());
mem_decl.has_value()) {
const auto& fun_decl = cast<FunctionDeclaration>(**mem_decl);
if (fun_decl.is_method()) {
return arena->New<BoundMethodValue>(&fun_decl, *me_value,
&impl_witness->bindings());
} else {
// Class function.
const auto* fun = cast<FunctionValue>(*fun_decl.constant_value());
return arena->New<FunctionValue>(&fun->declaration(),
&impl_witness->bindings());
}
} else {
return ProgramError(source_loc)
<< "member " << f << " not in " << *witness;
}
} else {
return ProgramError(source_loc)
<< "member lookup for " << f << " in symbolic " << *witness;
}
}
switch (v->kind()) {
case Value::Kind::StructValue: {
std::optional<Nonnull<const Value*>> field =
cast<StructValue>(*v).FindField(f);
if (field == std::nullopt) {
return ProgramError(source_loc) << "member " << f << " not in " << *v;
}
return *field;
}
case Value::Kind::NominalClassValue: {
const auto& object = cast<NominalClassValue>(*v);
// Look for a field.
if (std::optional<Nonnull<const Value*>> field =
FindClassField(&object, f)) {
return *field;
} else {
// Look for a method in the object's class
const auto& class_type = cast<NominalClassType>(object.type());
std::optional<Nonnull<const FunctionValue*>> func =
FindFunctionWithParents(f, class_type.declaration());
if (!func) {
return ProgramError(source_loc) << "member " << f << " not in " << *v
<< " or its " << class_type;
} else if ((*func)->declaration().is_method()) {
// Found a method. Turn it into a bound method.
const auto& m = cast<FunctionValue>(**func);
if (m.declaration().virt_override() == VirtualOverride::None) {
return arena->New<BoundMethodValue>(&m.declaration(), *me_value,
&class_type.bindings());
}
// Method is virtual, get child-most class value and perform vtable
// lookup.
const auto& last_child_value = **object.class_value_ptr();
const auto& last_child_type =
cast<NominalClassType>(last_child_value.type());
const auto res = last_child_type.vtable().find(f);
CARBON_CHECK(res != last_child_type.vtable().end());
const auto [virtual_method, level] = res->second;
const auto level_diff = last_child_type.hierarchy_level() - level;
const auto* m_class_value = &last_child_value;
// Get class value matching the virtual method, and turn it into a
// bound method.
for (int i = 0; i < level_diff; ++i) {
CARBON_CHECK(m_class_value->base(),
"Error trying to access function class value");
m_class_value = *m_class_value->base();
}
return arena->New<BoundMethodValue>(
cast<FunctionDeclaration>(virtual_method), m_class_value,
&class_type.bindings());
} else {
// Found a class function
// TODO: This should not be reachable.
return arena->New<FunctionValue>(&(*func)->declaration(),
&class_type.bindings());
}
}
}
case Value::Kind::ChoiceType: {
const auto& choice = cast<ChoiceType>(*v);
auto alt = choice.declaration().FindAlternative(f);
if (!alt) {
return ProgramError(source_loc)
<< "alternative " << f << " not in " << *v;
}
if ((*alt)->parameters()) {
return arena->New<AlternativeConstructorValue>(&choice, *alt);
}
return arena->New<AlternativeValue>(&choice, *alt, std::nullopt);
}
case Value::Kind::NominalClassType: {
// Access a class function.
const auto& class_type = cast<NominalClassType>(*v);
std::optional<Nonnull<const FunctionValue*>> fun =
FindFunctionWithParents(f, class_type.declaration());
if (fun == std::nullopt) {
return ProgramError(source_loc)
<< "class function " << f << " not in " << *v;
}
return arena->New<FunctionValue>(&(*fun)->declaration(),
&class_type.bindings());
}
default:
CARBON_FATAL("named element access not supported for value {0}", *v);
}
}
static auto GetElement(Nonnull<Arena*> arena, Nonnull<const Value*> v,
const ElementPath::Component& path_comp,
SourceLocation source_loc,
std::optional<Nonnull<const Value*>> me_value)
-> ErrorOr<Nonnull<const Value*>> {
switch (path_comp.element()->kind()) {
case ElementKind::NamedElement:
return GetNamedElement(arena, v, path_comp, source_loc, me_value);
case ElementKind::PositionalElement: {
if (const auto* tuple = dyn_cast<TupleValue>(v)) {
return GetPositionalElement(tuple, path_comp, source_loc);
} else {
CARBON_FATAL("Invalid value for positional element");
}
}
case ElementKind::BaseElement:
switch (v->kind()) {
case Value::Kind::NominalClassValue:
return GetBaseElement(cast<NominalClassValue>(v), source_loc);
case Value::Kind::PointerValue: {
const auto* ptr = cast<PointerValue>(v);
return arena->New<PointerValue>(
ptr->address().ElementAddress(path_comp.element()));
}
default:
CARBON_FATAL("Invalid value for base element");
}
}
}
auto Value::GetElement(Nonnull<Arena*> arena, const ElementPath& path,
SourceLocation source_loc,
std::optional<Nonnull<const Value*>> me_value) const
-> ErrorOr<Nonnull<const Value*>> {
Nonnull<const Value*> value(this);
for (const ElementPath::Component& field : path.components_) {
CARBON_ASSIGN_OR_RETURN(
value, Carbon::GetElement(arena, value, field, source_loc, me_value));
}
return value;
}
static auto SetFieldImpl(
Nonnull<Arena*> arena, Nonnull<const Value*> value,
std::vector<ElementPath::Component>::const_iterator path_begin,
std::vector<ElementPath::Component>::const_iterator path_end,
Nonnull<const Value*> field_value, SourceLocation source_loc)
-> ErrorOr<Nonnull<const Value*>> {
if (path_begin == path_end) {
return field_value;
}
switch (value->kind()) {
case Value::Kind::StructValue: {
std::vector<NamedValue> elements = cast<StructValue>(*value).elements();
auto it =
llvm::find_if(elements, [path_begin](const NamedValue& element) {
return (*path_begin).IsNamed(element.name);
});
if (it == elements.end()) {
return ProgramError(source_loc)
<< "field " << *path_begin << " not in " << *value;
}
CARBON_ASSIGN_OR_RETURN(
it->value, SetFieldImpl(arena, it->value, path_begin + 1, path_end,
field_value, source_loc));
return arena->New<StructValue>(elements);
}
case Value::Kind::NominalClassValue: {
const auto& object = cast<NominalClassValue>(*value);
if (auto inits = SetFieldImpl(arena, &object.inits(), path_begin,
path_end, field_value, source_loc);
inits.ok()) {
auto* class_value_ptr = arena->New<const NominalClassValue*>();
std::vector<const NominalClassValue*> base_path;
for (auto base = object.base(); base; base = (*base)->base()) {
base_path.push_back(*base);
}
std::optional<Nonnull<const NominalClassValue*>> base;
for (auto* base_path_elem : llvm::reverse(base_path)) {
base = arena->New<NominalClassValue>(&base_path_elem->type(),
&base_path_elem->inits(), base,
class_value_ptr);
}
return arena->New<NominalClassValue>(&object.type(), *inits, base,
class_value_ptr);
} else if (object.base().has_value()) {
auto new_base = SetFieldImpl(arena, object.base().value(), path_begin,
path_end, field_value, source_loc);
if (new_base.ok()) {
auto as_nominal_class_value = cast<NominalClassValue>(*new_base);
return arena->New<NominalClassValue>(
&object.type(), &object.inits(), as_nominal_class_value,
as_nominal_class_value->class_value_ptr());
}
}
// Failed to match, show full object content
return ProgramError(source_loc)
<< "field " << *path_begin << " not in " << *value;
}
case Value::Kind::TupleType:
case Value::Kind::TupleValue: {
CARBON_CHECK(
(*path_begin).element()->kind() == ElementKind::PositionalElement,
"Invalid non-positional member for tuple");
std::vector<Nonnull<const Value*>> elements =
cast<TupleValueBase>(*value).elements();
const size_t index =
cast<PositionalElement>((*path_begin).element())->index();
if (index < 0 || index >= elements.size()) {
return ProgramError(source_loc)
<< "index " << index << " out of range in " << *value;
}
CARBON_ASSIGN_OR_RETURN(
elements[index], SetFieldImpl(arena, elements[index], path_begin + 1,
path_end, field_value, source_loc));
if (isa<TupleType>(value)) {
return arena->New<TupleType>(elements);
} else {
return arena->New<TupleValue>(elements);
}
}
default:
CARBON_FATAL("field access not allowed for value {0}", *value);
}
}
auto Value::SetField(Nonnull<Arena*> arena, const ElementPath& path,
Nonnull<const Value*> field_value,
SourceLocation source_loc) const
-> ErrorOr<Nonnull<const Value*>> {
return SetFieldImpl(arena, static_cast<Nonnull<const Value*>>(this),
path.components_.begin(), path.components_.end(),
field_value, source_loc);
}
static auto PrintNameWithBindings(llvm::raw_ostream& out,
Nonnull<const Declaration*> declaration,
const BindingMap& args) {
out << GetName(*declaration).value_or("(anonymous)");
// TODO: Print '()' if declaration is parameterized but no args are provided.
if (!args.empty()) {
out << "(";
llvm::ListSeparator sep;
for (const auto& [bind, val] : args) {
out << sep << bind->name() << " = " << *val;
}
out << ")";
}
}
void Value::Print(llvm::raw_ostream& out) const {
switch (kind()) {
case Value::Kind::AlternativeConstructorValue: {
const auto& alt = cast<AlternativeConstructorValue>(*this);
out << alt.choice().declaration().name() << "."
<< alt.alternative().name();
break;
}
case Value::Kind::BindingPlaceholderValue: {
const auto& placeholder = cast<BindingPlaceholderValue>(*this);
out << "Placeholder<";
if (placeholder.value_node().has_value()) {
out << (*placeholder.value_node());
} else {
out << "_";
}
out << ">";
break;
}
case Value::Kind::AddrValue: {
const auto& addr = cast<AddrValue>(*this);
out << "Addr<" << addr.pattern() << ">";
break;
}
case Value::Kind::AlternativeValue: {
const auto& alt = cast<AlternativeValue>(*this);
out << alt.choice().declaration().name() << "."
<< alt.alternative().name();
if (auto arg = alt.argument()) {
out << **arg;
}
break;
}
case Value::Kind::StructValue: {
const auto& struct_val = cast<StructValue>(*this);
out << "{";
llvm::ListSeparator sep;
for (const NamedValue& element : struct_val.elements()) {
out << sep << "." << element.name << " = " << *element.value;
}
out << "}";
break;
}
case Value::Kind::NominalClassValue: {
const auto& s = cast<NominalClassValue>(*this);
out << cast<NominalClassType>(s.type()).declaration().name() << s.inits();
if (s.base().has_value()) {
out << " base " << *s.base().value();
}
break;
}
case Value::Kind::TupleType:
case Value::Kind::TupleValue: {
out << "(";
llvm::ListSeparator sep;
const auto elements = cast<TupleValueBase>(*this).elements();
for (Nonnull<const Value*> element : elements) {
out << sep << *element;
}
// Print trailing comma for single element tuples: (i32,).
if (elements.size() == 1) {
out << ",";
}
out << ")";
break;
}
case Value::Kind::IntValue:
out << cast<IntValue>(*this).value();
break;
case Value::Kind::BoolValue:
out << (cast<BoolValue>(*this).value() ? "true" : "false");
break;
case Value::Kind::DestructorValue: {
const auto& destructor = cast<DestructorValue>(*this);
out << "destructor [ ";
out << destructor.declaration().self_pattern();
out << " ]";
break;
}
case Value::Kind::FunctionValue: {
const auto& fun = cast<FunctionValue>(*this);
out << "fun<" << fun.declaration().name() << ">";
if (!fun.type_args().empty()) {
out << "[";
llvm::ListSeparator sep;
for (const auto& [ty_var, ty_arg] : fun.type_args()) {
out << sep << *ty_var << "=" << *ty_arg;
}
out << "]";
}
if (!fun.witnesses().empty()) {
out << "{|";
llvm::ListSeparator sep;
for (const auto& [impl_bind, witness] : fun.witnesses()) {
out << sep << *witness;
}
out << "|}";
}
break;
}
case Value::Kind::BoundMethodValue: {
const auto& method = cast<BoundMethodValue>(*this);
out << "bound_method<" << method.declaration().name() << ">";
if (!method.type_args().empty()) {
out << "[";
llvm::ListSeparator sep;
for (const auto& [ty_var, ty_arg] : method.type_args()) {
out << sep << *ty_var << "=" << *ty_arg;
}
out << "]";
}
if (!method.witnesses().empty()) {
out << "{|";
llvm::ListSeparator sep;
for (const auto& [impl_bind, witness] : method.witnesses()) {
out << sep << *witness;
}
out << "|}";
}
break;
}
case Value::Kind::PointerValue:
out << "ptr<" << cast<PointerValue>(*this).address() << ">";
break;
case Value::Kind::LocationValue:
out << "lval<" << cast<LocationValue>(*this).address() << ">";
break;
case Value::Kind::ReferenceExpressionValue:
out << "ref_expr<" << cast<ReferenceExpressionValue>(*this).address()
<< ">";
break;
case Value::Kind::BoolType:
out << "bool";
break;
case Value::Kind::IntType:
out << "i32";
break;
case Value::Kind::TypeType:
out << "type";
break;
case Value::Kind::AutoType:
out << "auto";
break;
case Value::Kind::PointerType:
out << cast<PointerType>(*this).pointee_type() << "*";
break;
case Value::Kind::FunctionType: {
const auto& fn_type = cast<FunctionType>(*this);
out << "fn ";
auto self = fn_type.method_self();
if (!fn_type.deduced_bindings().empty() || self.has_value()) {
out << "[";
llvm::ListSeparator sep;
for (Nonnull<const GenericBinding*> deduced :
fn_type.deduced_bindings()) {
out << sep << *deduced;
}
if (self.has_value()) {
if (self->addr_self) {
out << sep << "addr self: " << *self->self_type << "*";
} else {
out << sep << "self: " << *self->self_type;
}
}
out << "]";
}
out << fn_type.parameters() << " -> " << fn_type.return_type();
break;
}
case Value::Kind::StructType: {
out << "{";
llvm::ListSeparator sep;
for (const auto& [name, type] : cast<StructType>(*this).fields()) {
out << sep << "." << name << ": " << *type;
}
out << "}";
break;
}
case Value::Kind::UninitializedValue: {
const auto& uninit = cast<UninitializedValue>(*this);
out << "Uninit<" << uninit.pattern() << ">";
break;
}
case Value::Kind::NominalClassType: {
const auto& class_type = cast<NominalClassType>(*this);
out << "class ";
PrintNameWithBindings(out, &class_type.declaration(),
class_type.type_args());
if (!class_type.witnesses().empty()) {
out << " witnesses ";
llvm::ListSeparator sep;
for (const auto& [impl_bind, witness] : class_type.witnesses()) {
out << sep << *witness;
}
}
break;
}
case Value::Kind::ChoiceType: {
const auto& choice_type = cast<ChoiceType>(*this);
out << "choice ";
PrintNameWithBindings(out, &choice_type.declaration(),
choice_type.type_args());
break;
}
case Value::Kind::MixinPseudoType: {
const auto& mixin_type = cast<MixinPseudoType>(*this);
out << "mixin ";
PrintNameWithBindings(out, &mixin_type.declaration(), mixin_type.args());
if (!mixin_type.witnesses().empty()) {
out << " witnesses ";
llvm::ListSeparator sep;
for (const auto& [impl_bind, witness] : mixin_type.witnesses()) {
out << sep << *witness;
}
}
// TODO: print the import interface
break;
}
case Value::Kind::InterfaceType: {
const auto& iface_type = cast<InterfaceType>(*this);
out << "interface ";
PrintNameWithBindings(out, &iface_type.declaration(),
iface_type.bindings().args());
break;
}
case Value::Kind::NamedConstraintType: {
const auto& constraint_type = cast<NamedConstraintType>(*this);
out << "constraint ";
PrintNameWithBindings(out, &constraint_type.declaration(),
constraint_type.bindings().args());
break;
}
case Value::Kind::ConstraintType: {
const auto& constraint = cast<ConstraintType>(*this);
llvm::ListSeparator combine(" & ");
for (const LookupContext& ctx : constraint.lookup_contexts()) {
out << combine << *ctx.context;
}
if (constraint.lookup_contexts().empty()) {
out << "type";
}
out << " where ";
llvm::ListSeparator sep(" and ");
for (const RewriteConstraint& rewrite :
constraint.rewrite_constraints()) {
out << sep << ".(";
PrintNameWithBindings(out, &rewrite.constant->interface().declaration(),
rewrite.constant->interface().args());
out << "." << *GetName(rewrite.constant->constant())
<< ") = " << *rewrite.unconverted_replacement;
}
for (const ImplsConstraint& impl : constraint.impls_constraints()) {
// TODO: Skip cases where `impl.type` is `.Self` and the interface is
// in `lookup_contexts()`.
out << sep << *impl.type << " impls " << *impl.interface;
}
for (const EqualityConstraint& equality :
constraint.equality_constraints()) {
out << sep;
llvm::ListSeparator equal(" == ");
for (Nonnull<const Value*> value : equality.values) {
out << equal << *value;
}
}
break;
}
case Value::Kind::ImplWitness: {
const auto& witness = cast<ImplWitness>(*this);
out << "witness for impl " << *witness.declaration().impl_type() << " as "
<< witness.declaration().interface();
break;
}
case Value::Kind::BindingWitness: {
const auto& witness = cast<BindingWitness>(*this);
out << "witness for " << *witness.binding()->type_var();
break;
}
case Value::Kind::ConstraintWitness: {
const auto& witness = cast<ConstraintWitness>(*this);
out << "(";
llvm::ListSeparator sep;
for (const auto* elem : witness.witnesses()) {
out << sep << *elem;
}
out << ")";
break;
}
case Value::Kind::ConstraintImplWitness: {
const auto& witness = cast<ConstraintImplWitness>(*this);
out << "witness " << witness.index() << " of "
<< *witness.constraint_witness();
break;
}
case Value::Kind::ParameterizedEntityName:
out << *GetName(cast<ParameterizedEntityName>(*this).declaration());
break;
case Value::Kind::MemberName: {
const auto& member_name = cast<MemberName>(*this);
if (member_name.base_type().has_value()) {
out << *member_name.base_type().value();
}
if (member_name.base_type().has_value() &&
member_name.interface().has_value()) {
out << "(";
}
if (member_name.interface().has_value()) {
out << *member_name.interface().value();
}
out << "." << member_name.member();
if (member_name.base_type().has_value() &&
member_name.interface().has_value()) {
out << ")";
}
break;
}
case Value::Kind::VariableType:
out << cast<VariableType>(*this).binding().name();
break;
case Value::Kind::AssociatedConstant: {
const auto& assoc = cast<AssociatedConstant>(*this);
out << "(" << assoc.base() << ").(";
PrintNameWithBindings(out, &assoc.interface().declaration(),
assoc.interface().args());
out << "." << *GetName(assoc.constant()) << ")";
break;
}
case Value::Kind::StringType:
out << "String";
break;
case Value::Kind::StringValue:
out << "\"";
out.write_escaped(cast<StringValue>(*this).value());
out << "\"";
break;
case Value::Kind::TypeOfMixinPseudoType:
out << "typeof("
<< cast<TypeOfMixinPseudoType>(*this)
.mixin_type()
.declaration()
.name()
<< ")";
break;
case Value::Kind::TypeOfParameterizedEntityName:
out << "parameterized entity name "
<< cast<TypeOfParameterizedEntityName>(*this).name();
break;
case Value::Kind::TypeOfMemberName: {
out << "member name " << cast<TypeOfMemberName>(*this).member();
break;
}
case Value::Kind::TypeOfNamespaceName: {
cast<TypeOfNamespaceName>(*this).namespace_decl()->PrintID(out);
break;
}
case Value::Kind::StaticArrayType: {
const auto& array_type = cast<StaticArrayType>(*this);
out << "[" << array_type.element_type() << ";";
if (array_type.has_size()) {
out << " " << array_type.size();
}
out << "]";
break;
}
}
}
void IntrinsicConstraint::Print(llvm::raw_ostream& out) const {
out << *type << " is ";
switch (kind) {
case IntrinsicConstraint::ImplicitAs:
out << "__intrinsic_implicit_as";
break;
}
if (!arguments.empty()) {
out << "(";
llvm::ListSeparator comma;
for (Nonnull<const Value*> argument : arguments) {
out << comma << *argument;
}
out << ")";
}
}
// Check whether two binding maps, which are assumed to have the same keys, are
// equal.
static auto BindingMapEqual(
const BindingMap& map1, const BindingMap& map2,
std::optional<Nonnull<const EqualityContext*>> equality_ctx) -> bool {
CARBON_CHECK(map1.size() == map2.size(), "maps should have same keys");
for (const auto& [key, value] : map1) {
if (!ValueEqual(value, map2.at(key), equality_ctx)) {
return false;
}
}
return true;
}
auto TypeEqual(Nonnull<const Value*> t1, Nonnull<const Value*> t2,
std::optional<Nonnull<const EqualityContext*>> equality_ctx)
-> bool {
if (t1 == t2) {
return true;
}
if (t1->kind() != t2->kind()) {
if (IsValueKindDependent(t1) || IsValueKindDependent(t2)) {
return ValueEqual(t1, t2, equality_ctx);
}
return false;
}
switch (t1->kind()) {
case Value::Kind::PointerType:
return TypeEqual(&cast<PointerType>(*t1).pointee_type(),
&cast<PointerType>(*t2).pointee_type(), equality_ctx);
case Value::Kind::FunctionType: {
const auto& fn1 = cast<FunctionType>(*t1);
const auto& fn2 = cast<FunctionType>(*t2);
// Verify `self` parameters match
auto self1 = fn1.method_self();
auto self2 = fn2.method_self();
if (self1.has_value() != self2.has_value()) {
return false;
}
if (self1) {
if (self1->addr_self != self2->addr_self ||
!TypeEqual(self1->self_type, self2->self_type, equality_ctx)) {
return false;
}
}
// Verify parameters and return types match
return TypeEqual(&fn1.parameters(), &fn2.parameters(), equality_ctx) &&
TypeEqual(&fn1.return_type(), &fn2.return_type(), equality_ctx);
}
case Value::Kind::StructType: {
const auto& struct1 = cast<StructType>(*t1);
const auto& struct2 = cast<StructType>(*t2);
if (struct1.fields().size() != struct2.fields().size()) {
return false;
}
for (size_t i = 0; i < struct1.fields().size(); ++i) {
if (struct1.fields()[i].name != struct2.fields()[i].name ||
!TypeEqual(struct1.fields()[i].value, struct2.fields()[i].value,
equality_ctx)) {
return false;
}
}
return true;
}
case Value::Kind::NominalClassType: {
const auto& class1 = cast<NominalClassType>(*t1);
const auto& class2 = cast<NominalClassType>(*t2);
return DeclaresSameEntity(class1.declaration(), class2.declaration()) &&
BindingMapEqual(class1.bindings().args(), class2.bindings().args(),
equality_ctx);
}
case Value::Kind::InterfaceType: {
const auto& iface1 = cast<InterfaceType>(*t1);
const auto& iface2 = cast<InterfaceType>(*t2);
return DeclaresSameEntity(iface1.declaration(), iface2.declaration()) &&
BindingMapEqual(iface1.bindings().args(), iface2.bindings().args(),
equality_ctx);
}
case Value::Kind::NamedConstraintType: {
const auto& constraint1 = cast<NamedConstraintType>(*t1);
const auto& constraint2 = cast<NamedConstraintType>(*t2);
return DeclaresSameEntity(constraint1.declaration(),
constraint2.declaration()) &&
BindingMapEqual(constraint1.bindings().args(),
constraint2.bindings().args(), equality_ctx);
}
case Value::Kind::AssociatedConstant:
// Associated constants are sometimes types.
return ValueEqual(t1, t2, equality_ctx);
case Value::Kind::ConstraintType: {
const auto& constraint1 = cast<ConstraintType>(*t1);
const auto& constraint2 = cast<ConstraintType>(*t2);
if (constraint1.impls_constraints().size() !=
constraint2.impls_constraints().size() ||
constraint1.equality_constraints().size() !=
constraint2.equality_constraints().size() ||
constraint1.lookup_contexts().size() !=
constraint2.lookup_contexts().size()) {
return false;
}
for (size_t i = 0; i < constraint1.impls_constraints().size(); ++i) {
const auto& impl1 = constraint1.impls_constraints()[i];
const auto& impl2 = constraint2.impls_constraints()[i];
if (!TypeEqual(impl1.type, impl2.type, equality_ctx) ||
!TypeEqual(impl1.interface, impl2.interface, equality_ctx)) {
return false;
}
}
for (size_t i = 0; i < constraint1.equality_constraints().size(); ++i) {
const auto& equality1 = constraint1.equality_constraints()[i];
const auto& equality2 = constraint2.equality_constraints()[i];
if (equality1.values.size() != equality2.values.size()) {
return false;
}
for (size_t j = 0; j < equality1.values.size(); ++j) {
if (!ValueEqual(equality1.values[j], equality2.values[j],
equality_ctx)) {
return false;
}
}
}
for (size_t i = 0; i < constraint1.lookup_contexts().size(); ++i) {
const auto& context1 = constraint1.lookup_contexts()[i];
const auto& context2 = constraint2.lookup_contexts()[i];
if (!TypeEqual(context1.context, context2.context, equality_ctx)) {
return false;
}
}
return true;
}
case Value::Kind::ChoiceType: {
const auto& choice1 = cast<ChoiceType>(*t1);
const auto& choice2 = cast<ChoiceType>(*t2);
return DeclaresSameEntity(choice1.declaration(), choice2.declaration()) &&
BindingMapEqual(choice1.type_args(), choice2.type_args(),
equality_ctx);
}
case Value::Kind::TupleType:
case Value::Kind::TupleValue: {
const auto& tup1 = cast<TupleValueBase>(*t1);
const auto& tup2 = cast<TupleValueBase>(*t2);
if (tup1.elements().size() != tup2.elements().size()) {
return false;
}
for (size_t i = 0; i < tup1.elements().size(); ++i) {
if (!TypeEqual(tup1.elements()[i], tup2.elements()[i], equality_ctx)) {
return false;
}
}
return true;
}
case Value::Kind::IntType:
case Value::Kind::BoolType:
case Value::Kind::TypeType:
case Value::Kind::StringType:
return true;
case Value::Kind::VariableType:
return &cast<VariableType>(*t1).binding() ==
&cast<VariableType>(*t2).binding();
case Value::Kind::StaticArrayType: {
const auto& array1 = cast<StaticArrayType>(*t1);
const auto& array2 = cast<StaticArrayType>(*t2);