forked from carbon-language/carbon-lang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.cpp
1419 lines (1267 loc) · 54.2 KB
/
context.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 "toolchain/check/context.h"
#include <optional>
#include <string>
#include <utility>
#include "common/check.h"
#include "common/vlog.h"
#include "llvm/ADT/Sequence.h"
#include "toolchain/base/kind_switch.h"
#include "toolchain/check/decl_name_stack.h"
#include "toolchain/check/eval.h"
#include "toolchain/check/generic.h"
#include "toolchain/check/generic_region_stack.h"
#include "toolchain/check/import.h"
#include "toolchain/check/import_ref.h"
#include "toolchain/check/inst_block_stack.h"
#include "toolchain/check/merge.h"
#include "toolchain/diagnostics/diagnostic_emitter.h"
#include "toolchain/diagnostics/format_providers.h"
#include "toolchain/lex/tokenized_buffer.h"
#include "toolchain/parse/node_ids.h"
#include "toolchain/parse/node_kind.h"
#include "toolchain/sem_ir/file.h"
#include "toolchain/sem_ir/formatter.h"
#include "toolchain/sem_ir/generic.h"
#include "toolchain/sem_ir/ids.h"
#include "toolchain/sem_ir/import_ir.h"
#include "toolchain/sem_ir/inst.h"
#include "toolchain/sem_ir/inst_kind.h"
#include "toolchain/sem_ir/name_scope.h"
#include "toolchain/sem_ir/type_info.h"
#include "toolchain/sem_ir/typed_insts.h"
namespace Carbon::Check {
Context::Context(DiagnosticEmitter* emitter,
llvm::function_ref<const Parse::TreeAndSubtrees&()>
get_parse_tree_and_subtrees,
SemIR::File* sem_ir, llvm::raw_ostream* vlog_stream)
: emitter_(emitter),
get_parse_tree_and_subtrees_(get_parse_tree_and_subtrees),
sem_ir_(sem_ir),
vlog_stream_(vlog_stream),
node_stack_(sem_ir->parse_tree(), vlog_stream),
inst_block_stack_("inst_block_stack_", *sem_ir, vlog_stream),
pattern_block_stack_("pattern_block_stack_", *sem_ir, vlog_stream),
param_and_arg_refs_stack_(*sem_ir, vlog_stream, node_stack_),
args_type_info_stack_("args_type_info_stack_", *sem_ir, vlog_stream),
decl_name_stack_(this),
scope_stack_(sem_ir_->identifiers()),
global_init_(this) {
// Map the builtin `<error>` and `type` type constants to their corresponding
// special `TypeId` values.
type_ids_for_type_constants_.Insert(
SemIR::ConstantId::ForTemplateConstant(SemIR::ErrorInst::SingletonInstId),
SemIR::ErrorInst::SingletonTypeId);
type_ids_for_type_constants_.Insert(
SemIR::ConstantId::ForTemplateConstant(SemIR::TypeType::SingletonInstId),
SemIR::TypeType::SingletonTypeId);
// TODO: Remove this and add a `VerifyOnFinish` once we properly push and pop
// in the right places.
generic_region_stack().Push();
}
auto Context::TODO(SemIRLoc loc, std::string label) -> bool {
CARBON_DIAGNOSTIC(SemanticsTodo, Error, "semantics TODO: `{0}`", std::string);
emitter_->Emit(loc, SemanticsTodo, std::move(label));
return false;
}
auto Context::VerifyOnFinish() -> void {
// Information in all the various context objects should be cleaned up as
// various pieces of context go out of scope. At this point, nothing should
// remain.
// node_stack_ will still contain top-level entities.
inst_block_stack_.VerifyOnFinish();
pattern_block_stack_.VerifyOnFinish();
param_and_arg_refs_stack_.VerifyOnFinish();
args_type_info_stack_.VerifyOnFinish();
CARBON_CHECK(struct_type_fields_stack_.empty());
// TODO: Add verification for decl_name_stack_ and
// decl_introducer_state_stack_.
scope_stack_.VerifyOnFinish();
// TODO: Add verification for generic_region_stack_.
}
auto Context::GetOrAddInst(SemIR::LocIdAndInst loc_id_and_inst)
-> SemIR::InstId {
if (loc_id_and_inst.loc_id.is_implicit()) {
auto const_id =
TryEvalInst(*this, SemIR::InstId::Invalid, loc_id_and_inst.inst);
if (const_id.is_valid()) {
CARBON_VLOG("GetOrAddInst: constant: {0}\n", loc_id_and_inst.inst);
return constant_values().GetInstId(const_id);
}
}
// TODO: For an implicit instruction, this reattempts evaluation.
return AddInst(loc_id_and_inst);
}
// Finish producing an instruction. Set its constant value, and register it in
// any applicable instruction lists.
auto Context::FinishInst(SemIR::InstId inst_id, SemIR::Inst inst) -> void {
GenericRegionStack::DependencyKind dep_kind =
GenericRegionStack::DependencyKind::None;
// If the instruction has a symbolic constant type, track that we need to
// substitute into it.
if (constant_values().DependsOnGenericParameter(
types().GetConstantId(inst.type_id()))) {
dep_kind |= GenericRegionStack::DependencyKind::SymbolicType;
}
// If the instruction has a constant value, compute it.
auto const_id = TryEvalInst(*this, inst_id, inst);
constant_values().Set(inst_id, const_id);
if (const_id.is_constant()) {
CARBON_VLOG("Constant: {0} -> {1}\n", inst,
constant_values().GetInstId(const_id));
// If the constant value is symbolic, track that we need to substitute into
// it.
if (constant_values().DependsOnGenericParameter(const_id)) {
dep_kind |= GenericRegionStack::DependencyKind::SymbolicConstant;
}
}
// Keep track of dependent instructions.
if (dep_kind != GenericRegionStack::DependencyKind::None) {
// TODO: Also check for template-dependent instructions.
generic_region_stack().AddDependentInst(
{.inst_id = inst_id, .kind = dep_kind});
}
}
// Returns whether a parse node associated with an imported instruction of kind
// `imported_kind` is usable as the location of a corresponding local
// instruction of kind `local_kind`.
static auto HasCompatibleImportedNodeKind(SemIR::InstKind imported_kind,
SemIR::InstKind local_kind) -> bool {
if (imported_kind == local_kind) {
return true;
}
if (imported_kind == SemIR::ImportDecl::Kind &&
local_kind == SemIR::Namespace::Kind) {
static_assert(
std::is_convertible_v<decltype(SemIR::ImportDecl::Kind)::TypedNodeId,
decltype(SemIR::Namespace::Kind)::TypedNodeId>);
return true;
}
return false;
}
auto Context::CheckCompatibleImportedNodeKind(
SemIR::ImportIRInstId imported_loc_id, SemIR::InstKind kind) -> void {
auto& import_ir_inst = import_ir_insts().Get(imported_loc_id);
const auto* import_ir = import_irs().Get(import_ir_inst.ir_id).sem_ir;
auto imported_kind = import_ir->insts().Get(import_ir_inst.inst_id).kind();
CARBON_CHECK(
HasCompatibleImportedNodeKind(imported_kind, kind),
"Node of kind {0} created with location of imported node of kind {1}",
kind, imported_kind);
}
auto Context::AddPlaceholderInstInNoBlock(SemIR::LocIdAndInst loc_id_and_inst)
-> SemIR::InstId {
auto inst_id = sem_ir().insts().AddInNoBlock(loc_id_and_inst);
CARBON_VLOG("AddPlaceholderInst: {0}\n", loc_id_and_inst.inst);
constant_values().Set(inst_id, SemIR::ConstantId::Invalid);
return inst_id;
}
auto Context::AddPlaceholderInst(SemIR::LocIdAndInst loc_id_and_inst)
-> SemIR::InstId {
auto inst_id = AddPlaceholderInstInNoBlock(loc_id_and_inst);
inst_block_stack_.AddInstId(inst_id);
return inst_id;
}
auto Context::ReplaceLocIdAndInstBeforeConstantUse(
SemIR::InstId inst_id, SemIR::LocIdAndInst loc_id_and_inst) -> void {
sem_ir().insts().SetLocIdAndInst(inst_id, loc_id_and_inst);
CARBON_VLOG("ReplaceInst: {0} -> {1}\n", inst_id, loc_id_and_inst.inst);
FinishInst(inst_id, loc_id_and_inst.inst);
}
auto Context::ReplaceInstBeforeConstantUse(SemIR::InstId inst_id,
SemIR::Inst inst) -> void {
sem_ir().insts().Set(inst_id, inst);
CARBON_VLOG("ReplaceInst: {0} -> {1}\n", inst_id, inst);
FinishInst(inst_id, inst);
}
auto Context::ReplaceInstPreservingConstantValue(SemIR::InstId inst_id,
SemIR::Inst inst) -> void {
auto old_const_id = sem_ir().constant_values().Get(inst_id);
sem_ir().insts().Set(inst_id, inst);
CARBON_VLOG("ReplaceInst: {0} -> {1}\n", inst_id, inst);
auto new_const_id = TryEvalInst(*this, inst_id, inst);
CARBON_CHECK(old_const_id == new_const_id);
}
auto Context::DiagnoseDuplicateName(SemIRLoc dup_def, SemIRLoc prev_def)
-> void {
CARBON_DIAGNOSTIC(NameDeclDuplicate, Error,
"duplicate name being declared in the same scope");
CARBON_DIAGNOSTIC(NameDeclPrevious, Note, "name is previously declared here");
emitter_->Build(dup_def, NameDeclDuplicate)
.Note(prev_def, NameDeclPrevious)
.Emit();
}
auto Context::DiagnoseNameNotFound(SemIRLoc loc, SemIR::NameId name_id)
-> void {
CARBON_DIAGNOSTIC(NameNotFound, Error, "name `{0}` not found", SemIR::NameId);
emitter_->Emit(loc, NameNotFound, name_id);
}
auto Context::NoteAbstractClass(SemIR::ClassId class_id,
DiagnosticBuilder& builder) -> void {
const auto& class_info = classes().Get(class_id);
CARBON_CHECK(
class_info.inheritance_kind == SemIR::Class::InheritanceKind::Abstract,
"Class is not abstract");
CARBON_DIAGNOSTIC(ClassAbstractHere, Note,
"class was declared abstract here");
builder.Note(class_info.definition_id, ClassAbstractHere);
}
auto Context::NoteIncompleteClass(SemIR::ClassId class_id,
DiagnosticBuilder& builder) -> void {
const auto& class_info = classes().Get(class_id);
CARBON_CHECK(!class_info.is_defined(), "Class is not incomplete");
if (class_info.definition_id.is_valid()) {
CARBON_DIAGNOSTIC(ClassIncompleteWithinDefinition, Note,
"class is incomplete within its definition");
builder.Note(class_info.definition_id, ClassIncompleteWithinDefinition);
} else {
CARBON_DIAGNOSTIC(ClassForwardDeclaredHere, Note,
"class was forward declared here");
builder.Note(class_info.latest_decl_id(), ClassForwardDeclaredHere);
}
}
auto Context::NoteUndefinedInterface(SemIR::InterfaceId interface_id,
DiagnosticBuilder& builder) -> void {
const auto& interface_info = interfaces().Get(interface_id);
CARBON_CHECK(!interface_info.is_defined(), "Interface is not incomplete");
if (interface_info.is_being_defined()) {
CARBON_DIAGNOSTIC(InterfaceUndefinedWithinDefinition, Note,
"interface is currently being defined");
builder.Note(interface_info.definition_id,
InterfaceUndefinedWithinDefinition);
} else {
CARBON_DIAGNOSTIC(InterfaceForwardDeclaredHere, Note,
"interface was forward declared here");
builder.Note(interface_info.latest_decl_id(), InterfaceForwardDeclaredHere);
}
}
auto Context::AddNameToLookup(SemIR::NameId name_id, SemIR::InstId target_id)
-> void {
if (auto existing = scope_stack().LookupOrAddName(name_id, target_id);
existing.is_valid()) {
DiagnoseDuplicateName(target_id, existing);
}
}
auto Context::LookupNameInDecl(SemIR::LocId loc_id, SemIR::NameId name_id,
SemIR::NameScopeId scope_id) -> SemIR::InstId {
if (!scope_id.is_valid()) {
// Look for a name in the current scope only. There are two cases where the
// name would be in an outer scope:
//
// - The name is the sole component of the declared name:
//
// class A;
// fn F() {
// class A;
// }
//
// In this case, the inner A is not the same class as the outer A, so
// lookup should not find the outer A.
//
// - The name is a qualifier of some larger declared name:
//
// class A { class B; }
// fn F() {
// class A.B {}
// }
//
// In this case, we're not in the correct scope to define a member of
// class A, so we should reject, and we achieve this by not finding the
// name A from the outer scope.
return scope_stack().LookupInCurrentScope(name_id);
} else {
// We do not look into `extend`ed scopes here. A qualified name in a
// declaration must specify the exact scope in which the name was originally
// introduced:
//
// base class A { fn F(); }
// class B { extend base: A; }
//
// // Error, no `F` in `B`.
// fn B.F() {}
return LookupNameInExactScope(loc_id, name_id, scope_id,
name_scopes().Get(scope_id))
.first;
}
}
auto Context::LookupUnqualifiedName(Parse::NodeId node_id,
SemIR::NameId name_id, bool required)
-> LookupResult {
// TODO: Check for shadowed lookup results.
// Find the results from ancestor lexical scopes. These will be combined with
// results from non-lexical scopes such as namespaces and classes.
auto [lexical_result, non_lexical_scopes] =
scope_stack().LookupInLexicalScopes(name_id);
// Walk the non-lexical scopes and perform lookups into each of them.
for (auto [index, lookup_scope_id, specific_id] :
llvm::reverse(non_lexical_scopes)) {
if (auto non_lexical_result =
LookupQualifiedName(node_id, name_id,
LookupScope{.name_scope_id = lookup_scope_id,
.specific_id = specific_id},
/*required=*/false);
non_lexical_result.inst_id.is_valid()) {
return non_lexical_result;
}
}
if (lexical_result.is_valid()) {
// A lexical scope never needs an associated specific. If there's a
// lexically enclosing generic, then it also encloses the point of use of
// the name.
return {.specific_id = SemIR::SpecificId::Invalid,
.inst_id = lexical_result};
}
// We didn't find anything at all.
if (required) {
DiagnoseNameNotFound(node_id, name_id);
}
return {.specific_id = SemIR::SpecificId::Invalid,
.inst_id = SemIR::ErrorInst::SingletonInstId};
}
auto Context::LookupNameInExactScope(SemIRLoc loc, SemIR::NameId name_id,
SemIR::NameScopeId scope_id,
const SemIR::NameScope& scope)
-> std::pair<SemIR::InstId, SemIR::AccessKind> {
if (auto entry_id = scope.Lookup(name_id)) {
auto entry = scope.GetEntry(*entry_id);
LoadImportRef(*this, entry.inst_id);
return {entry.inst_id, entry.access_kind};
}
if (!scope.import_ir_scopes().empty()) {
// TODO: Enforce other access modifiers for imports.
return {ImportNameFromOtherPackage(*this, loc, scope_id,
scope.import_ir_scopes(), name_id),
SemIR::AccessKind::Public};
}
return {SemIR::InstId::Invalid, SemIR::AccessKind::Public};
}
// Prints diagnostics on invalid qualified name access.
static auto DiagnoseInvalidQualifiedNameAccess(Context& context, SemIRLoc loc,
SemIR::InstId scope_result_id,
SemIR::NameId name_id,
SemIR::AccessKind access_kind,
bool is_parent_access,
AccessInfo access_info) -> void {
auto class_type = context.insts().TryGetAs<SemIR::ClassType>(
context.constant_values().GetInstId(access_info.constant_id));
if (!class_type) {
return;
}
// TODO: Support scoped entities other than just classes.
const auto& class_info = context.classes().Get(class_type->class_id);
auto parent_type_id = class_info.self_type_id;
if (access_kind == SemIR::AccessKind::Private && is_parent_access) {
if (auto base_type_id =
class_info.GetBaseType(context.sem_ir(), class_type->specific_id);
base_type_id.is_valid()) {
parent_type_id = base_type_id;
} else if (auto adapted_type_id = class_info.GetAdaptedType(
context.sem_ir(), class_type->specific_id);
adapted_type_id.is_valid()) {
parent_type_id = adapted_type_id;
} else {
CARBON_FATAL("Expected parent for parent access");
}
}
CARBON_DIAGNOSTIC(
ClassInvalidMemberAccess, Error,
"cannot access {0:private|protected} member `{1}` of type {2}",
BoolAsSelect, SemIR::NameId, SemIR::TypeId);
CARBON_DIAGNOSTIC(ClassMemberDeclaration, Note, "declared here");
context.emitter()
.Build(loc, ClassInvalidMemberAccess,
access_kind == SemIR::AccessKind::Private, name_id, parent_type_id)
.Note(scope_result_id, ClassMemberDeclaration)
.Emit();
}
// Returns whether the access is prohibited by the access modifiers.
static auto IsAccessProhibited(std::optional<AccessInfo> access_info,
SemIR::AccessKind access_kind,
bool is_parent_access) -> bool {
if (!access_info) {
return false;
}
switch (access_kind) {
case SemIR::AccessKind::Public:
return false;
case SemIR::AccessKind::Protected:
return access_info->highest_allowed_access == SemIR::AccessKind::Public;
case SemIR::AccessKind::Private:
return access_info->highest_allowed_access !=
SemIR::AccessKind::Private ||
is_parent_access;
}
}
// Information regarding a prohibited access.
struct ProhibitedAccessInfo {
// The resulting inst of the lookup.
SemIR::InstId scope_result_id;
// The access kind of the lookup.
SemIR::AccessKind access_kind;
// If the lookup is from an extended scope. For example, if this is a base
// class member access from a class that extends it.
bool is_parent_access;
};
auto Context::AppendLookupScopesForConstant(
SemIRLoc loc, SemIR::ConstantId base_const_id,
llvm::SmallVector<LookupScope>* scopes) -> bool {
auto base_id = constant_values().GetInstId(base_const_id);
auto base = insts().Get(base_id);
if (auto base_as_namespace = base.TryAs<SemIR::Namespace>()) {
scopes->push_back(
LookupScope{.name_scope_id = base_as_namespace->name_scope_id,
.specific_id = SemIR::SpecificId::Invalid});
return true;
}
if (auto base_as_class = base.TryAs<SemIR::ClassType>()) {
TryToDefineType(GetTypeIdForTypeConstant(base_const_id), [&] {
CARBON_DIAGNOSTIC(QualifiedExprInIncompleteClassScope, Error,
"member access into incomplete class {0}",
InstIdAsType);
return emitter().Build(loc, QualifiedExprInIncompleteClassScope, base_id);
});
auto& class_info = classes().Get(base_as_class->class_id);
scopes->push_back(LookupScope{.name_scope_id = class_info.scope_id,
.specific_id = base_as_class->specific_id});
return true;
}
if (auto base_as_facet_type = base.TryAs<SemIR::FacetType>()) {
TryToDefineType(GetTypeIdForTypeConstant(base_const_id), [&] {
CARBON_DIAGNOSTIC(QualifiedExprInUndefinedInterfaceScope, Error,
"member access into undefined interface {0}",
InstIdAsType);
return emitter().Build(loc, QualifiedExprInUndefinedInterfaceScope,
base_id);
});
const auto& facet_type_info =
facet_types().Get(base_as_facet_type->facet_type_id);
for (auto interface : facet_type_info.impls_constraints) {
auto& interface_info = interfaces().Get(interface.interface_id);
scopes->push_back(LookupScope{.name_scope_id = interface_info.scope_id,
.specific_id = interface.specific_id});
}
return true;
}
if (base_const_id == SemIR::ErrorInst::SingletonConstantId) {
// Lookup into this scope should fail without producing an error.
scopes->push_back(LookupScope{.name_scope_id = SemIR::NameScopeId::Invalid,
.specific_id = SemIR::SpecificId::Invalid});
return true;
}
// TODO: Per the design, if `base_id` is any kind of type, then lookup should
// treat it as a name scope, even if it doesn't have members. For example,
// `(i32*).X` should fail because there's no name `X` in `i32*`, not because
// there's no name `X` in `type`.
return false;
}
auto Context::LookupQualifiedName(SemIRLoc loc, SemIR::NameId name_id,
llvm::ArrayRef<LookupScope> lookup_scopes,
bool required,
std::optional<AccessInfo> access_info)
-> LookupResult {
llvm::SmallVector<LookupScope> scopes(lookup_scopes);
// TODO: Support reporting of multiple prohibited access.
llvm::SmallVector<ProhibitedAccessInfo> prohibited_accesses;
LookupResult result = {.specific_id = SemIR::SpecificId::Invalid,
.inst_id = SemIR::InstId::Invalid};
bool has_error = false;
bool is_parent_access = false;
// Walk this scope and, if nothing is found here, the scopes it extends.
while (!scopes.empty()) {
auto [scope_id, specific_id] = scopes.pop_back_val();
if (!scope_id.is_valid()) {
has_error = true;
continue;
}
const auto& name_scope = name_scopes().Get(scope_id);
has_error |= name_scope.has_error();
auto [scope_result_id, access_kind] =
LookupNameInExactScope(loc, name_id, scope_id, name_scope);
auto is_access_prohibited =
IsAccessProhibited(access_info, access_kind, is_parent_access);
// Keep track of prohibited accesses, this will be useful for reporting
// multiple prohibited accesses if we can't find a suitable lookup.
if (is_access_prohibited) {
prohibited_accesses.push_back({
.scope_result_id = scope_result_id,
.access_kind = access_kind,
.is_parent_access = is_parent_access,
});
}
if (!scope_result_id.is_valid() || is_access_prohibited) {
// If nothing is found in this scope or if we encountered an invalid
// access, look in its extended scopes.
const auto& extended = name_scope.extended_scopes();
scopes.reserve(scopes.size() + extended.size());
for (auto extended_id : llvm::reverse(extended)) {
// Substitute into the constant describing the extended scope to
// determine its corresponding specific.
CARBON_CHECK(extended_id.is_valid());
LoadImportRef(*this, extended_id);
SemIR::ConstantId const_id =
GetConstantValueInSpecific(sem_ir(), specific_id, extended_id);
DiagnosticAnnotationScope annotate_diagnostics(
&emitter(), [&](auto& builder) {
CARBON_DIAGNOSTIC(FromExtendHere, Note,
"declared as an extended scope here");
builder.Note(extended_id, FromExtendHere);
});
if (!AppendLookupScopesForConstant(loc, const_id, &scopes)) {
// TODO: Handle case where we have a symbolic type and instead should
// look in its type.
}
}
is_parent_access |= !extended.empty();
continue;
}
// If this is our second lookup result, diagnose an ambiguity.
if (result.inst_id.is_valid()) {
CARBON_DIAGNOSTIC(
NameAmbiguousDueToExtend, Error,
"ambiguous use of name `{0}` found in multiple extended scopes",
SemIR::NameId);
emitter_->Emit(loc, NameAmbiguousDueToExtend, name_id);
// TODO: Add notes pointing to the scopes.
return {.specific_id = SemIR::SpecificId::Invalid,
.inst_id = SemIR::ErrorInst::SingletonInstId};
}
result.inst_id = scope_result_id;
result.specific_id = specific_id;
}
if (required && !result.inst_id.is_valid()) {
if (!has_error) {
if (prohibited_accesses.empty()) {
DiagnoseNameNotFound(loc, name_id);
} else {
// TODO: We should report multiple prohibited accesses in case we don't
// find a valid lookup. Reporting the last one should suffice for now.
auto [scope_result_id, access_kind, is_parent_access] =
prohibited_accesses.back();
// Note, `access_info` is guaranteed to have a value here, since
// `prohibited_accesses` is non-empty.
DiagnoseInvalidQualifiedNameAccess(*this, loc, scope_result_id, name_id,
access_kind, is_parent_access,
*access_info);
}
}
return {.specific_id = SemIR::SpecificId::Invalid,
.inst_id = SemIR::ErrorInst::SingletonInstId};
}
return result;
}
// Returns the scope of the Core package, or Invalid if it's not found.
//
// TODO: Consider tracking the Core package in SemIR so we don't need to use
// name lookup to find it.
static auto GetCorePackage(Context& context, SemIRLoc loc, llvm::StringRef name)
-> SemIR::NameScopeId {
auto core_ident_id = context.identifiers().Add("Core");
auto packaging = context.parse_tree().packaging_decl();
if (packaging && packaging->names.package_id == core_ident_id) {
return SemIR::NameScopeId::Package;
}
auto core_name_id = SemIR::NameId::ForIdentifier(core_ident_id);
// Look up `package.Core`.
auto [core_inst_id, _] = context.LookupNameInExactScope(
loc, core_name_id, SemIR::NameScopeId::Package,
context.name_scopes().Get(SemIR::NameScopeId::Package));
if (core_inst_id.is_valid()) {
// We expect it to be a namespace.
if (auto namespace_inst =
context.insts().TryGetAs<SemIR::Namespace>(core_inst_id)) {
// TODO: Decide whether to allow the case where `Core` is not a package.
return namespace_inst->name_scope_id;
}
}
CARBON_DIAGNOSTIC(
CoreNotFound, Error,
"`Core.{0}` implicitly referenced here, but package `Core` not found",
std::string);
context.emitter().Emit(loc, CoreNotFound, name.str());
return SemIR::NameScopeId::Invalid;
}
auto Context::LookupNameInCore(SemIRLoc loc, llvm::StringRef name)
-> SemIR::InstId {
auto core_package_id = GetCorePackage(*this, loc, name);
if (!core_package_id.is_valid()) {
return SemIR::ErrorInst::SingletonInstId;
}
auto name_id = SemIR::NameId::ForIdentifier(identifiers().Add(name));
auto [inst_id, _] = LookupNameInExactScope(
loc, name_id, core_package_id, name_scopes().Get(core_package_id));
if (!inst_id.is_valid()) {
CARBON_DIAGNOSTIC(
CoreNameNotFound, Error,
"name `Core.{0}` implicitly referenced here, but not found",
SemIR::NameId);
emitter_->Emit(loc, CoreNameNotFound, name_id);
return SemIR::ErrorInst::SingletonInstId;
}
// Look through import_refs and aliases.
return constant_values().GetConstantInstId(inst_id);
}
template <typename BranchNode, typename... Args>
static auto AddDominatedBlockAndBranchImpl(Context& context,
Parse::NodeId node_id, Args... args)
-> SemIR::InstBlockId {
if (!context.inst_block_stack().is_current_block_reachable()) {
return SemIR::InstBlockId::Unreachable;
}
auto block_id = context.inst_blocks().AddDefaultValue();
context.AddInst<BranchNode>(node_id, {block_id, args...});
return block_id;
}
auto Context::AddDominatedBlockAndBranch(Parse::NodeId node_id)
-> SemIR::InstBlockId {
return AddDominatedBlockAndBranchImpl<SemIR::Branch>(*this, node_id);
}
auto Context::AddDominatedBlockAndBranchWithArg(Parse::NodeId node_id,
SemIR::InstId arg_id)
-> SemIR::InstBlockId {
return AddDominatedBlockAndBranchImpl<SemIR::BranchWithArg>(*this, node_id,
arg_id);
}
auto Context::AddDominatedBlockAndBranchIf(Parse::NodeId node_id,
SemIR::InstId cond_id)
-> SemIR::InstBlockId {
return AddDominatedBlockAndBranchImpl<SemIR::BranchIf>(*this, node_id,
cond_id);
}
auto Context::AddConvergenceBlockAndPush(Parse::NodeId node_id, int num_blocks)
-> void {
CARBON_CHECK(num_blocks >= 2, "no convergence");
SemIR::InstBlockId new_block_id = SemIR::InstBlockId::Unreachable;
for ([[maybe_unused]] auto _ : llvm::seq(num_blocks)) {
if (inst_block_stack().is_current_block_reachable()) {
if (new_block_id == SemIR::InstBlockId::Unreachable) {
new_block_id = inst_blocks().AddDefaultValue();
}
AddInst<SemIR::Branch>(node_id, {.target_id = new_block_id});
}
inst_block_stack().Pop();
}
inst_block_stack().Push(new_block_id);
}
auto Context::AddConvergenceBlockWithArgAndPush(
Parse::NodeId node_id, std::initializer_list<SemIR::InstId> block_args)
-> SemIR::InstId {
CARBON_CHECK(block_args.size() >= 2, "no convergence");
SemIR::InstBlockId new_block_id = SemIR::InstBlockId::Unreachable;
for (auto arg_id : block_args) {
if (inst_block_stack().is_current_block_reachable()) {
if (new_block_id == SemIR::InstBlockId::Unreachable) {
new_block_id = inst_blocks().AddDefaultValue();
}
AddInst<SemIR::BranchWithArg>(
node_id, {.target_id = new_block_id, .arg_id = arg_id});
}
inst_block_stack().Pop();
}
inst_block_stack().Push(new_block_id);
// Acquire the result value.
SemIR::TypeId result_type_id = insts().Get(*block_args.begin()).type_id();
return AddInst<SemIR::BlockArg>(
node_id, {.type_id = result_type_id, .block_id = new_block_id});
}
auto Context::SetBlockArgResultBeforeConstantUse(SemIR::InstId select_id,
SemIR::InstId cond_id,
SemIR::InstId if_true,
SemIR::InstId if_false)
-> void {
CARBON_CHECK(insts().Is<SemIR::BlockArg>(select_id));
// Determine the constant result based on the condition value.
SemIR::ConstantId const_id = SemIR::ConstantId::NotConstant;
auto cond_const_id = constant_values().Get(cond_id);
if (!cond_const_id.is_template()) {
// Symbolic or non-constant condition means a non-constant result.
} else if (auto literal = insts().TryGetAs<SemIR::BoolLiteral>(
constant_values().GetInstId(cond_const_id))) {
const_id = constant_values().Get(literal.value().value.ToBool() ? if_true
: if_false);
} else {
CARBON_CHECK(cond_const_id == SemIR::ErrorInst::SingletonConstantId,
"Unexpected constant branch condition.");
const_id = SemIR::ErrorInst::SingletonConstantId;
}
if (const_id.is_constant()) {
CARBON_VLOG("Constant: {0} -> {1}\n", insts().Get(select_id),
constant_values().GetInstId(const_id));
constant_values().Set(select_id, const_id);
}
}
auto Context::AddCurrentCodeBlockToFunction(Parse::NodeId node_id) -> void {
CARBON_CHECK(!inst_block_stack().empty(), "no current code block");
if (return_scope_stack().empty()) {
CARBON_CHECK(node_id.is_valid(),
"No current function, but node_id not provided");
TODO(node_id,
"Control flow expressions are currently only supported inside "
"functions.");
return;
}
if (!inst_block_stack().is_current_block_reachable()) {
// Don't include unreachable blocks in the function.
return;
}
auto function_id =
insts()
.GetAs<SemIR::FunctionDecl>(return_scope_stack().back().decl_id)
.function_id;
functions()
.Get(function_id)
.body_block_ids.push_back(inst_block_stack().PeekOrAdd());
}
auto Context::is_current_position_reachable() -> bool {
if (!inst_block_stack().is_current_block_reachable()) {
return false;
}
// Our current position is at the end of a reachable block. That position is
// reachable unless the previous instruction is a terminator instruction.
auto block_contents = inst_block_stack().PeekCurrentBlockContents();
if (block_contents.empty()) {
return true;
}
const auto& last_inst = insts().Get(block_contents.back());
return last_inst.kind().terminator_kind() !=
SemIR::TerminatorKind::Terminator;
}
auto Context::Finalize() -> void {
// Pop information for the file-level scope.
sem_ir().set_top_inst_block_id(inst_block_stack().Pop());
scope_stack().Pop();
// Finalizes the list of exports on the IR.
inst_blocks().Set(SemIR::InstBlockId::Exports, exports_);
// Finalizes the ImportRef inst block.
inst_blocks().Set(SemIR::InstBlockId::ImportRefs, import_ref_ids_);
// Finalizes __global_init.
global_init_.Finalize();
}
namespace {
// Worklist-based type completion mechanism.
//
// When attempting to complete a type, we may find other types that also need to
// be completed: types nested within that type, and the value representation of
// the type. In order to complete a type without recursing arbitrarily deeply,
// we use a worklist of tasks:
//
// - An `AddNestedIncompleteTypes` step adds a task for all incomplete types
// nested within a type to the work list.
// - A `BuildValueRepr` step computes the value representation for a
// type, once all of its nested types are complete, and marks the type as
// complete.
class TypeCompleter {
public:
TypeCompleter(Context& context, Context::BuildDiagnosticFn diagnoser)
: context_(context), diagnoser_(diagnoser) {}
// Attempts to complete the given type. Returns true if it is now complete,
// false if it could not be completed.
auto Complete(SemIR::TypeId type_id) -> bool {
Push(type_id);
while (!work_list_.empty()) {
if (!ProcessStep()) {
return false;
}
}
return true;
}
private:
// Adds `type_id` to the work list, if it's not already complete.
auto Push(SemIR::TypeId type_id) -> void {
if (!context_.types().IsComplete(type_id)) {
work_list_.push_back(
{.type_id = type_id, .phase = Phase::AddNestedIncompleteTypes});
}
}
// Runs the next step.
auto ProcessStep() -> bool {
auto [type_id, phase] = work_list_.back();
// We might have enqueued the same type more than once. Just skip the
// type if it's already complete.
if (context_.types().IsComplete(type_id)) {
work_list_.pop_back();
return true;
}
auto inst_id = context_.types().GetInstId(type_id);
auto inst = context_.insts().Get(inst_id);
auto old_work_list_size = work_list_.size();
switch (phase) {
case Phase::AddNestedIncompleteTypes:
if (!AddNestedIncompleteTypes(inst)) {
return false;
}
CARBON_CHECK(work_list_.size() >= old_work_list_size,
"AddNestedIncompleteTypes should not remove work items");
work_list_[old_work_list_size - 1].phase = Phase::BuildValueRepr;
break;
case Phase::BuildValueRepr: {
auto value_rep = BuildValueRepr(type_id, inst);
context_.types().SetValueRepr(type_id, value_rep);
CARBON_CHECK(old_work_list_size == work_list_.size(),
"BuildValueRepr should not change work items");
work_list_.pop_back();
// Also complete the value representation type, if necessary. This
// should never fail: the value representation shouldn't require any
// additional nested types to be complete.
if (!context_.types().IsComplete(value_rep.type_id)) {
work_list_.push_back(
{.type_id = value_rep.type_id, .phase = Phase::BuildValueRepr});
}
// For a pointer representation, the pointee also needs to be complete.
if (value_rep.kind == SemIR::ValueRepr::Pointer) {
if (value_rep.type_id == SemIR::ErrorInst::SingletonTypeId) {
break;
}
auto pointee_type_id =
context_.sem_ir().GetPointeeType(value_rep.type_id);
if (!context_.types().IsComplete(pointee_type_id)) {
work_list_.push_back(
{.type_id = pointee_type_id, .phase = Phase::BuildValueRepr});
}
}
break;
}
}
return true;
}
// Adds any types nested within `type_inst` that need to be complete for
// `type_inst` to be complete to our work list.
auto AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool {
CARBON_KIND_SWITCH(type_inst) {
case CARBON_KIND(SemIR::ArrayType inst): {
Push(inst.element_type_id);
break;
}
case CARBON_KIND(SemIR::StructType inst): {
for (auto field : context_.struct_type_fields().Get(inst.fields_id)) {
Push(field.type_id);
}
break;
}
case CARBON_KIND(SemIR::TupleType inst): {
for (auto element_type_id :
context_.type_blocks().Get(inst.elements_id)) {
Push(element_type_id);
}
break;
}
case CARBON_KIND(SemIR::ClassType inst): {
auto& class_info = context_.classes().Get(inst.class_id);
if (!class_info.is_defined()) {
if (diagnoser_) {
auto builder = diagnoser_();
context_.NoteIncompleteClass(inst.class_id, builder);
builder.Emit();
}
return false;
}
if (inst.specific_id.is_valid()) {
ResolveSpecificDefinition(context_, inst.specific_id);
}
if (auto adapted_type_id =
class_info.GetAdaptedType(context_.sem_ir(), inst.specific_id);
adapted_type_id.is_valid()) {
Push(adapted_type_id);
} else {
Push(class_info.GetObjectRepr(context_.sem_ir(), inst.specific_id));
}
break;
}
case CARBON_KIND(SemIR::ConstType inst): {
Push(inst.inner_id);
break;
}
default:
break;
}
return true;
}
// Makes an empty value representation, which is used for types that have no
// state, such as empty structs and tuples.
auto MakeEmptyValueRepr() const -> SemIR::ValueRepr {
return {.kind = SemIR::ValueRepr::None,
.type_id = context_.GetTupleType({})};
}
// Makes a value representation that uses pass-by-copy, copying the given
// type.
auto MakeCopyValueRepr(SemIR::TypeId rep_id,
SemIR::ValueRepr::AggregateKind aggregate_kind =
SemIR::ValueRepr::NotAggregate) const
-> SemIR::ValueRepr {
return {.kind = SemIR::ValueRepr::Copy,
.aggregate_kind = aggregate_kind,
.type_id = rep_id};
}
// Makes a value representation that uses pass-by-address with the given
// pointee type.
auto MakePointerValueRepr(SemIR::TypeId pointee_id,
SemIR::ValueRepr::AggregateKind aggregate_kind =