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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
|
// slang-lookup.cpp
#include "slang-lookup.h"
#include "../compiler-core/slang-name.h"
#include "slang-check-impl.h"
// TODO(tfoley): The implementation of lookup still involves
// recursion over the structure of a type/declaration, but
// it should be possible for it to use the flattened/linearized
// inheritance information that is being computed in
// `slang-check-inheritance.cpp`.
namespace Slang
{
void ensureDecl(SemanticsVisitor* visitor, Decl* decl, DeclCheckState state);
//
DeclRef<ExtensionDecl> applyExtensionToType(
SemanticsVisitor* semantics,
ExtensionDecl* extDecl,
Type* type);
//
// Helper for constructing breadcrumb trails during lookup, without unnecessary heap allocaiton
struct BreadcrumbInfo
{
LookupResultItem::Breadcrumb::Kind kind;
LookupResultItem::Breadcrumb::ThisParameterMode thisParameterMode =
LookupResultItem::Breadcrumb::ThisParameterMode::Default;
DeclRef<Decl> declRef;
Val* val = nullptr;
BreadcrumbInfo* prev = nullptr;
};
//
bool DeclPassesLookupMask(Decl* decl, LookupMask mask)
{
// Always exclude extern members from lookup result.
if (decl->hasModifier<ExtensionExternVarModifier>())
{
return false;
}
else if (decl->hasModifier<ExternModifier>())
{
if (as<ExtensionDecl>(decl->parentDecl))
{
return false;
}
}
// type declarations
if (const auto aggTypeDecl = as<AggTypeDecl>(decl))
{
return int(mask) & int(LookupMask::type);
}
else if (const auto simpleTypeDecl = as<SimpleTypeDecl>(decl))
{
return int(mask) & int(LookupMask::type);
}
// function declarations
else if (const auto funcDecl = as<FunctionDeclBase>(decl))
{
return (int(mask) & int(LookupMask::Function)) != 0;
}
// attribute declaration
else if (const auto attrDecl = as<AttributeDecl>(decl))
{
return (int(mask) & int(LookupMask::Attribute)) != 0;
}
// syntax declaration
else if (const auto syntaxDecl = as<SyntaxDecl>(decl))
{
return (int(mask) & int(LookupMask::SyntaxDecl)) != 0;
}
// default behavior is to assume a value declaration
// (no overloading allowed)
return (int(mask) & int(LookupMask::Value)) != 0;
}
void AddToLookupResult(LookupResult& result, LookupResultItem item)
{
if (!result.isValid())
{
// If we hadn't found a hit before, we have one now
result.item = item;
}
else if (!result.isOverloaded())
{
// We are about to make this overloaded
result.items.add(result.item);
result.items.add(item);
}
else
{
// The result was already overloaded, so we pile on
result.items.add(item);
}
}
void AddToLookupResult(LookupResult& result, const LookupResult& items)
{
if (items.isOverloaded())
{
for (auto item : items.items)
AddToLookupResult(result, item);
}
else if (items.isValid())
{
AddToLookupResult(result, items.item);
}
}
LookupResult refineLookup(LookupResult const& inResult, LookupMask mask)
{
if (!inResult.isValid())
return inResult;
if (!inResult.isOverloaded())
return inResult;
LookupResult result;
for (auto item : inResult.items)
{
if (!DeclPassesLookupMask(item.declRef.getDecl(), mask))
continue;
AddToLookupResult(result, item);
}
return result;
}
LookupResultItem CreateLookupResultItem(DeclRef<Decl> declRef, BreadcrumbInfo* breadcrumbInfos)
{
LookupResultItem item;
item.declRef = declRef;
// breadcrumbs were constructed "backwards" on the stack, so we
// reverse them here by building a linked list the other way
RefPtr<LookupResultItem::Breadcrumb> breadcrumbs;
for (auto bb = breadcrumbInfos; bb; bb = bb->prev)
{
breadcrumbs = new LookupResultItem::Breadcrumb(
bb->kind,
bb->declRef,
bb->val,
breadcrumbs,
bb->thisParameterMode);
}
item.breadcrumbs = breadcrumbs;
return item;
}
static void _lookUpMembersInValue(
ASTBuilder* astBuilder,
Name* name,
DeclRef<Decl> valueDeclRef,
LookupRequest const& request,
LookupResult& ioResult,
BreadcrumbInfo* breadcrumbs);
static bool _isUncheckedLocalVar(const Decl* decl)
{
auto checkStateExt = decl->checkState;
auto isUnchecked = checkStateExt.getState() == DeclCheckState::Unchecked ||
checkStateExt.isBeingChecked() || decl->hiddenFromLookup;
return isUnchecked && isLocalVar(decl);
}
/// Look up direct members (those declared in `containerDeclRef` itself, as well
/// as transitively through any direct members that are marked "transparent."
///
/// This function does *not* deal with looking up through `extension`s,
/// inheritance clauses, etc.
///
static void _lookUpDirectAndTransparentMembers(
ASTBuilder* astBuilder,
Name* name,
ContainerDecl* containerDecl, // The container decl to find member with `name`.
DeclRef<Decl> parentDeclRef, // The parent of the resulting declref.
LookupRequest const& request,
LookupResult& result,
BreadcrumbInfo* inBreadcrumbs)
{
if (request.isCompletionRequest())
{
// If we are looking up for completion suggestions,
// return all the members that are available.
for (auto member : containerDecl->getDirectMemberDecls())
{
if (!request.shouldConsiderAllLocalNames() && _isUncheckedLocalVar(member))
continue;
if (!DeclPassesLookupMask(member, request.mask))
continue;
AddToLookupResult(
result,
CreateLookupResultItem(
astBuilder->getMemberDeclRef<Decl>(parentDeclRef, member),
inBreadcrumbs));
}
}
else
{
// Iterate over the declarations with the chosen name in the container
// (if any), and see if we find any that meet our filtering criteria.
//
// For example, we might be filtering so that we only consider
// type declarations.
//
for (auto m : containerDecl->getDirectMemberDeclsOfName(name))
{
// Skip this declaration if we are checking and this hasn't been
// checked yet. Because we traverse block statements in order, if
// it's unchecked or being checked then it isn't declared yet.
if (!request.shouldConsiderAllLocalNames() && request.semantics &&
_isUncheckedLocalVar(m))
continue;
if (m == request.declToExclude)
continue;
if (!DeclPassesLookupMask(m, request.mask))
continue;
// The declaration passed the test, so add it!
AddToLookupResult(
result,
CreateLookupResultItem(
astBuilder->getMemberDeclRef<Decl>(parentDeclRef, m),
inBreadcrumbs));
}
}
// Don't look up transparent members if we are looking for attributes, since
// they are always defined at global scope in the core module. Trying to lookup transparent
// members during attribute lookup can lead to infinite recursion on transparent types.
if ((int)request.mask & (int)LookupMask::Attribute)
return;
// Also skip transparent members if they're explicitly excluded by the
// request. This prevents cyclic lookups e.g. when looking up UnscopedEnum's
// underlying types.
if (((int)request.options & (int)LookupOptions::IgnoreTransparentMembers) != 0)
return;
for (auto transparentMemberDecl : containerDecl->getTransparentDirectMemberDecls())
{
// The reference to the transparent member should use the same
// path as we used in referring to its parent.
DeclRef<Decl> transparentMemberDeclRef =
astBuilder->getMemberDeclRef(parentDeclRef, transparentMemberDecl);
if (transparentMemberDeclRef.getDecl() == request.declToExclude)
continue;
// We need to leave a breadcrumb so that we know that the result
// of lookup involves a member lookup step here
BreadcrumbInfo memberRefBreadcrumb;
memberRefBreadcrumb.kind = LookupResultItem::Breadcrumb::Kind::Member;
memberRefBreadcrumb.declRef = transparentMemberDeclRef;
memberRefBreadcrumb.prev = inBreadcrumbs;
_lookUpMembersInValue(
astBuilder,
name,
transparentMemberDeclRef,
request,
result,
&memberRefBreadcrumb);
}
}
LookupRequest initLookupRequest(
SemanticsVisitor* semantics,
Name* name,
LookupMask mask,
LookupOptions options,
Scope* scope,
Decl* declToExclude)
{
LookupRequest request;
request.semantics = semantics;
request.mask = mask;
request.options = options;
request.scope = scope;
request.declToExclude = declToExclude;
if (semantics && semantics->getSession() &&
name == semantics->getSession()->getCompletionRequestTokenName())
request.options = (LookupOptions)((int)request.options | (int)LookupOptions::Completion);
return request;
}
/// Perform "direct" lookup in a container declaration
LookupResult lookUpDirectAndTransparentMembers(
ASTBuilder* astBuilder,
SemanticsVisitor* semantics,
Name* name,
ContainerDecl* containerDecl,
DeclRef<Decl> parentDeclRef,
LookupMask mask,
Decl* declToExclude)
{
LookupRequest request =
initLookupRequest(semantics, name, mask, LookupOptions::None, nullptr, declToExclude);
LookupResult result;
_lookUpDirectAndTransparentMembers(
astBuilder,
name,
containerDecl,
parentDeclRef,
request,
result,
nullptr);
return result;
}
// Specialize `declRefToSpecialize` with ThisType info if `superType` is an interface type.
DeclRef<Decl> _maybeSpecializeSuperTypeDeclRef(
ASTBuilder* astBuilder,
DeclRef<Decl> declRefToSpecialize,
Type* superType,
SubtypeWitness* subIsSuperWitness)
{
if (auto superDeclRefType = as<DeclRefType>(superType))
{
if (auto superInterfaceDeclRef = superDeclRefType->getDeclRef().as<InterfaceDecl>())
{
ThisTypeDecl* thisTypeDecl = superInterfaceDeclRef.getDecl()->getThisTypeDecl();
auto specializedDeclRef = astBuilder->getLookupDeclRef(subIsSuperWitness, thisTypeDecl);
return specializedDeclRef;
}
}
return declRefToSpecialize;
}
// Same as the above, but we are specializing a type instead of a decl-ref
static Type* _maybeSpecializeSuperType(
ASTBuilder* astBuilder,
Type* superType,
SubtypeWitness* subIsSuperWitness)
{
if (auto superDeclRefType = as<DeclRefType>(superType))
{
auto specializedDeclRef = _maybeSpecializeSuperTypeDeclRef(
astBuilder,
superDeclRefType->getDeclRef(),
superType,
subIsSuperWitness);
return DeclRefType::create(astBuilder, specializedDeclRef);
}
return superType;
}
void FacetImpl::init(ASTBuilder* astBuilder)
{
if (directness != Facet::Directness::Self)
{
// Depending on the type of the facet, we may want to specialize the
// declRef that we are going to lookup in. If the facet represents
// an extension, we should just lookup in the extension decl.
//
// If the facet is an extension to an interface type, we should
// specialize the interface declRef to the concrete type that this
// extension applied to.
//
// If the facet represents an implementation of interface type,
// we should also specialize the interface declRef with the concrete
// type info.
//
declRefForMemberLookup =
_maybeSpecializeSuperTypeDeclRef(astBuilder, origin.declRef, getType(), subtypeWitness)
.as<ContainerDecl>();
}
else
{
declRefForMemberLookup = origin.declRef.as<ContainerDecl>();
}
}
static void _lookUpMembersInType(
ASTBuilder* astBuilder,
Name* name,
Type* type,
LookupRequest const& request,
LookupResult& ioResult,
BreadcrumbInfo* breadcrumbs);
static void _lookUpMembersInSuperTypeImpl(
ASTBuilder* astBuilder,
Name* name,
Type* leafType,
Type* superType,
SubtypeWitness* leafIsSuperWitness,
LookupRequest const& request,
LookupResult& ioResult,
BreadcrumbInfo* inBreadcrumbs);
static void _lookUpMembersInSuperType(
ASTBuilder* astBuilder,
Name* name,
Type* leafType,
Type* superType,
SubtypeWitness* leafIsSuperWitness,
LookupRequest const& request,
LookupResult& ioResult,
BreadcrumbInfo* inBreadcrumbs)
{
// If we are looking up through an interface type, then
// we need to be sure that we add an appropriate
// "this type" substitution here, since that needs to
// be applied to any members we look up.
//
superType = _maybeSpecializeSuperType(astBuilder, superType, leafIsSuperWitness);
// We need to track the indirection we took in lookup,
// so that we can construct an appropriate AST on the other
// side that includes the "upcast" from sub-type to super-type.
//
BreadcrumbInfo breadcrumb;
breadcrumb.prev = inBreadcrumbs;
breadcrumb.kind = LookupResultItem::Breadcrumb::Kind::SuperType;
breadcrumb.val = leafIsSuperWitness;
breadcrumb.prev = inBreadcrumbs;
_lookUpMembersInSuperTypeImpl(
astBuilder,
name,
leafType,
superType,
leafIsSuperWitness,
request,
ioResult,
&breadcrumb);
}
static void _lookupMembersInSuperTypeFacets(
ASTBuilder* astBuilder,
Name* name,
Type* selfType,
InheritanceInfo const& inheritanceInfo,
LookupRequest const& request,
LookupResult& ioResult,
BreadcrumbInfo* inBreadcrumbs)
{
for (auto facet : inheritanceInfo.facets)
{
auto containerDeclRef = facet->getDeclRef().as<ContainerDecl>();
if (!containerDeclRef)
continue;
// Check for cases where we should skip this facet for lookup.
//
// If the facet doesn't correspond to a type, we can't lookup.
if (!facet->getType() || !facet->subtypeWitness)
{
continue;
}
// If we are looking up in an interface, and the lookup request told us
// to skip interfaces, we should do so here.
if (auto baseInterfaceDeclRef = containerDeclRef.as<InterfaceDecl>())
{
if (int(request.options) & int(LookupOptions::IgnoreBaseInterfaces))
continue;
}
// If we are looking up only immediate members, ignore non "Self" facets or extension to
// "Self"
else if (
int(request.options) & int(LookupOptions::IgnoreInheritance) &&
(facet.getImpl()->directness != Facet::Directness::Self))
{
if (auto extensionDeclRef = facet.getImpl()->getDeclRef().as<ExtensionDecl>())
{
if (auto targetType = getTargetType(astBuilder, extensionDeclRef))
{
if (!targetType->equals(selfType))
{
// If the extension is to the same type as the one we are looking up in, we
// should include it in the lookup.
continue;
}
}
}
else
continue;
}
// Some things that are syntactically `InheritanceDecl`s don't actually
// represent a subtype/supertype relationship, and thus we shouldn't
// include members from the base type when doing lookup in the
// derived type.
//
// TODO: this check currently only works when the facet is a direct
// basee type of the type we are looking up in. This is OK because the
// only case where we use `IgnoreForLookupModifier` is for skipping the
// underlying int type of an enum type. We should either makes this
// check more general, or just explicitly detect this case here without
// relying on the modifier.
if (auto declaredSubtypeWitness = as<DeclaredSubtypeWitness>(facet->subtypeWitness))
{
auto inheritanceDeclRef = declaredSubtypeWitness->getDeclRef();
if (inheritanceDeclRef.getDecl()->hasModifier<IgnoreForLookupModifier>())
continue;
}
// We are now going to lookup in the facet.
BreadcrumbInfo* newBreadcrumbs = inBreadcrumbs;
BreadcrumbInfo subtypeInfo;
auto parentDeclRef = facet->declRefForMemberLookup;
if (facet->directness != Facet::Directness::Self)
{
if (as<ThisTypeDecl>(parentDeclRef.getDecl()) && getText(name) == "This")
{
// If we are going looking for `This` in a `ThisType`, we just need to return the
// declRef itself.
AddToLookupResult(ioResult, CreateLookupResultItem(parentDeclRef, inBreadcrumbs));
continue;
}
// If we are looking up in a base type, we also need to make sure
// to create a breadcrumb to track the sub to super indirection.
if (facet->kind == Facet::Kind::Type)
{
subtypeInfo.kind = LookupResultItem_Breadcrumb::Kind::SuperType;
subtypeInfo.val = facet->subtypeWitness;
subtypeInfo.prev = inBreadcrumbs;
subtypeInfo.declRef = facet->getDeclRef();
newBreadcrumbs = &subtypeInfo;
}
}
_lookUpDirectAndTransparentMembers(
astBuilder,
name,
containerDeclRef.getDecl(),
parentDeclRef,
request,
ioResult,
newBreadcrumbs);
}
}
static void _lookUpMembersInSuperTypeDeclImpl(
ASTBuilder* astBuilder,
Name* name,
DeclRef<Decl> declRef,
LookupRequest const& request,
LookupResult& ioResult,
BreadcrumbInfo* inBreadcrumbs)
{
auto semantics = request.semantics;
if (!as<InterfaceDecl>(declRef.getDecl()) &&
name == astBuilder->getSharedASTBuilder()->getThisTypeName())
{
// If we are looking for `This` in anything other than an InterfaceDecl,
// we just need to return the declRef itself.
AddToLookupResult(ioResult, CreateLookupResultItem(declRef, inBreadcrumbs));
return;
}
// If the semantics context hasn't been established yet (e.g. when looking up during parsing),
// we simply do a direct lookup without considering subtypes or extensions.
//
if (!semantics)
{
// In this case we can only lookup in an aggregate type.
if (auto aggTypeDeclBaseRef = declRef.as<AggTypeDeclBase>())
{
_lookUpDirectAndTransparentMembers(
astBuilder,
name,
aggTypeDeclBaseRef.getDecl(),
aggTypeDeclBaseRef,
request,
ioResult,
inBreadcrumbs);
}
return;
}
ensureDecl(semantics, declRef.getDecl(), DeclCheckState::ReadyForLookup);
// With semantics context, we can do a comprehensive lookup by scanning through
// the linearized inheritance list.
auto selfType = DeclRefType::create(astBuilder, declRef);
InheritanceInfo inheritanceInfo;
if (auto extDeclRef = declRef.as<ExtensionDecl>())
{
inheritanceInfo = semantics->getShared()->getInheritanceInfo(extDeclRef);
}
else
{
selfType = selfType->getCanonicalType();
inheritanceInfo = semantics->getShared()->getInheritanceInfo(selfType);
}
_lookupMembersInSuperTypeFacets(
astBuilder,
name,
selfType,
inheritanceInfo,
request,
ioResult,
inBreadcrumbs);
}
static void _lookUpMembersInSuperTypeImpl(
ASTBuilder* astBuilder,
Name* name,
Type* leafType,
Type* superType,
SubtypeWitness* leafIsSuperWitness,
LookupRequest const& request,
LookupResult& ioResult,
BreadcrumbInfo* inBreadcrumbs)
{
// If the type was pointer-like, then dereference it
// automatically here.
if (((uint32_t)request.options & (uint32_t)LookupOptions::NoDeref) == 0)
{
if (auto pointerElementType = getPointedToTypeIfCanImplicitDeref(superType))
{
// Need to leave a breadcrumb to indicate that we
// did an implicit dereference here
BreadcrumbInfo derefBreacrumb;
derefBreacrumb.kind = LookupResultItem::Breadcrumb::Kind::Deref;
derefBreacrumb.prev = inBreadcrumbs;
// Recursively perform lookup on the result of deref
_lookUpMembersInType(
astBuilder,
name,
pointerElementType,
request,
ioResult,
&derefBreacrumb);
if (ioResult.isValid())
return;
}
}
// Default case: no dereference needed
if (auto declRefType = as<DeclRefType>(superType))
{
auto declRef = declRefType->getDeclRef();
_lookUpMembersInSuperTypeDeclImpl(
astBuilder,
name,
declRef,
request,
ioResult,
inBreadcrumbs);
}
else if (auto eachType = as<EachType>(superType))
{
auto canEachType = eachType->getCanonicalType();
InheritanceInfo inheritanceInfo =
request.semantics->getShared()->getInheritanceInfo(canEachType);
_lookupMembersInSuperTypeFacets(
astBuilder,
name,
canEachType,
inheritanceInfo,
request,
ioResult,
inBreadcrumbs);
}
else if (auto extractExistentialType = as<ExtractExistentialType>(superType))
{
// We want lookup to be performed on the underlying interface type of the existential,
// but we need to have a this-type substitution applied to ensure that the result of
// lookup will have a comparable substitution applied (allowing things like associated
// types, etc. used in the signature of a method to resolve correctly).
//
auto thisTypeDeclRef = extractExistentialType->getThisTypeDeclRef();
_lookUpMembersInSuperTypeDeclImpl(
astBuilder,
name,
thisTypeDeclRef,
request,
ioResult,
inBreadcrumbs);
}
else if (auto andType = as<AndType>(superType))
{
// We have a type of the form `leftType & rightType` and we need to perform
// lookup in both `leftType` and `rightType`.
//
auto leftType = andType->getLeft();
auto rightType = andType->getRight();
// Operationally, we are in a situation where we have a witness
// that the `leafType` we are doing lookup on is an subtype
// of `superType` (which is `leftType & rightType`) and now we need
// to construct a witness that `leafType` is a subtype of
// the `Left` type.
//
// Effectively, we have a witness that `T : X & Y` and we
// need to extract from it a witness that `T : X`.
//
//
auto leafIsLeftWitness = astBuilder->getExtractFromConjunctionSubtypeWitness(
leafType,
leftType,
leafIsSuperWitness,
0);
// The witness for the fact that `leafType : rightType` is the
// same as for the left case, just with a different index into
// the conjunction.
//
auto leafIsRightWitness = astBuilder->getExtractFromConjunctionSubtypeWitness(
leafType,
rightType,
leafIsSuperWitness,
1);
// We then perform lookup on both sides of the conjunction, and
// accumulate whatever items are found on either/both sides.
//
// For each recursive lookup, we pass the appropriate pair of
// the type to look up in and the witness of the subtype
// relationship.
//
_lookUpMembersInSuperType(
astBuilder,
name,
leafType,
leftType,
leafIsLeftWitness,
request,
ioResult,
inBreadcrumbs);
_lookUpMembersInSuperType(
astBuilder,
name,
leafType,
rightType,
leafIsRightWitness,
request,
ioResult,
inBreadcrumbs);
}
}
/// Perform lookup for `name` in the context of `type`.
///
/// This operation does the kind of lookup we'd expect if `name`
/// was used inside of a member function on `type`, or if the
/// user wrote `obj.<name>` for a variable `obj` of the given
/// `type`.
///
/// Looking up members in `type` includes lookup through any
/// constraints or inheritance relationships that expand the
/// set of members visible on `type`.
///
static void _lookUpMembersInType(
ASTBuilder* astBuilder,
Name* name,
Type* type,
LookupRequest const& request,
LookupResult& ioResult,
BreadcrumbInfo* breadcrumbs)
{
if (!type)
{
return;
}
_lookUpMembersInSuperTypeImpl(
astBuilder,
name,
type,
type,
nullptr,
request,
ioResult,
breadcrumbs);
}
/// Look up members by `name` in the given `valueDeclRef`.
///
/// If `valueDeclRef` represents a reference to a variable
/// or other named and typed value, then this performs the
/// kind of lookup we'd expect for `valueDeclRef.<name>`.
///
static void _lookUpMembersInValue(
ASTBuilder* astBuilder,
Name* name,
DeclRef<Decl> valueDeclRef,
LookupRequest const& request,
LookupResult& ioResult,
BreadcrumbInfo* breadcrumbs)
{
// Looking up `name` in the context of a value can
// be reduced to the problem of looking up `name`
// in the *type* of that value.
//
auto valueType = getTypeForDeclRef(astBuilder, valueDeclRef, SourceLoc());
if (auto typeType = as<TypeType>(valueType))
valueType = typeType->getType();
return _lookUpMembersInType(astBuilder, name, valueType, request, ioResult, breadcrumbs);
}
// True if the declaration is of an overloadable variety
// (ie can have multiple definitions with the same name)
//
// For example functions are overloadable, but variables are (typically) not.
static bool _isDeclOverloadable(Decl* decl)
{
// If it's a generic strip off, to get to inner decl type
while (auto genericDecl = as<GenericDecl>(decl))
{
decl = genericDecl->inner;
}
// TODO(JS): Do we need to special case around ConstructorDecl? or AccessorDecl?
// It seems not as they are both function-like and potentially overloadable
// If it's callable, it's a function-like and so overloadable
if (auto callableDecl = as<CallableDecl>(decl))
{
SLANG_UNUSED(callableDecl);
return true;
}
return false;
}
static void _lookUpInScopes(
ASTBuilder* astBuilder,
Name* name,
LookupRequest const& request,
LookupResult& result)
{
auto thisParameterMode = LookupResultItem::Breadcrumb::ThisParameterMode::Default;
auto scope = request.scope;
auto endScope = request.endScope;
// The file decl that this scope is in.
FileDecl* thisFileDecl = nullptr;
for (; scope != endScope; scope = scope->parent)
{
// Note that we consider all "peer" scopes together,
// so that a hit in one of them does not preclude
// also finding a hit in another
for (auto link = scope; link; link = link->nextSibling)
{
auto containerDecl = link->containerDecl;
// It is possible for the first scope in a list of
// siblings to be a "dummy" scope that only exists
// to combine the siblings; in that case it will
// have a null `containerDecl` and needs to be
// skipped over.
//
if (!containerDecl)
continue;
if (auto fileDecl = as<FileDecl>(containerDecl))
{
if (!thisFileDecl)
thisFileDecl = fileDecl;
else if (fileDecl == thisFileDecl)
{
// If we have already looked up in this file decl,
// we don't want to do so again.
continue;
}
}
// TODO: If we need default substitutions to be applied to
// the `containerDecl`, then it might make sense to have
// each `link` in the scope store a decl-ref instead of
// just a decl.
//
DeclRef<ContainerDecl> containerDeclRef = createDefaultSubstitutionsIfNeeded(
astBuilder,
request.semantics,
makeDeclRef(containerDecl))
.as<ContainerDecl>();
// If the container we are looking into represents a type
// or an `extension` of a type, then we need to treat
// this step as lookup into the `this` variable (or the
// `This` type), which means including any `extension`s
// or inheritance clauses in the lookup process.
//
// Note: The `AggTypeDeclBase` class is the common superclass
// between `AggTypeDecl` and `ExtensionDecl`.
//
if (auto aggTypeDeclBaseRef = containerDeclRef.as<AggTypeDeclBase>())
{
// When reconstructing the final expression for a result
// looked up through the type or extension, we will need
// a `this` expression (or a `This` type expression) to
// mark the base of the member reference, so we create
// a "breadcrumb" here to track that fact.
//
BreadcrumbInfo breadcrumb;
breadcrumb.kind = LookupResultItem::Breadcrumb::Kind::This;
breadcrumb.thisParameterMode = thisParameterMode;
breadcrumb.declRef = aggTypeDeclBaseRef;
breadcrumb.prev = nullptr;
BreadcrumbInfo* breadcrumbPtr = &breadcrumb;
Type* type = nullptr;
if (auto extDeclRef = aggTypeDeclBaseRef.as<ExtensionDecl>())
{
if (request.semantics)
{
ensureDecl(
request.semantics,
extDeclRef.getDecl(),
DeclCheckState::CanUseExtensionTargetType);
}
// If we are doing lookup from inside an `extension`
// declaration, then the `this` expression will have
// a type that uses the "target type" of the `extension`.
//
type = getTargetType(astBuilder, extDeclRef);
if (name == astBuilder->getSharedASTBuilder()->getThisTypeName())
{
breadcrumbPtr = nullptr;
}
}
else
{
assert(aggTypeDeclBaseRef.as<AggTypeDecl>());
if (auto interfaceBase = as<InterfaceDecl>(aggTypeDeclBaseRef.getDecl()))
{
// When looking up inside an interface type, we are actually looking up
// through ThisType.
if (name != interfaceBase->getThisTypeDecl()->getName())
{
type = DeclRefType::create(
astBuilder,
astBuilder->getMemberDeclRef(
aggTypeDeclBaseRef,
interfaceBase->getThisTypeDecl()));
// Don't need any breadcrumb for looking up through ThisType, since we
// have already created the base type reference in the new `type`'s
// declref.
breadcrumbPtr = nullptr;
}
}
if (!type)
{
type = DeclRefType::create(astBuilder, aggTypeDeclBaseRef);
}
}
// When looking up in an extension declaration, we should not automatically
// dereference pointer types, as the 'This' type should refer to the
// extension target type itself, not the pointed-to type.
LookupRequest modifiedRequest = request;
if (aggTypeDeclBaseRef.as<ExtensionDecl>())
{
modifiedRequest.options = (LookupOptions)((uint32_t)modifiedRequest.options |
(uint32_t)LookupOptions::NoDeref);
}
_lookUpMembersInType(
astBuilder,
name,
type,
modifiedRequest,
result,
breadcrumbPtr);
}
else
{
// The default case is when the scope doesn't represent a
// type or `extension` declaration, so we can look up members
// in that scope much more simply.
//
_lookUpDirectAndTransparentMembers(
astBuilder,
name,
containerDeclRef.getDecl(),
containerDeclRef,
request,
result,
nullptr);
}
if (auto defaultImplDecl = as<InterfaceDefaultImplDecl>(containerDecl))
{
// If we are checking an interface default method implementation,
// we should look up members from implicit `this` whose type is the explicit `This`
// generic parameter, and skip looking up in the interface decl itself.
// Instead of looking up in the interface decl itself, we should
// look up in the `This` type instead.
if (getText(name) != "This")
{
BreadcrumbInfo breadcrumb;
breadcrumb.kind = LookupResultItem::Breadcrumb::Kind::This;
breadcrumb.thisParameterMode = thisParameterMode;
breadcrumb.declRef = DeclRef<Decl>(defaultImplDecl->thisTypeDecl);
breadcrumb.prev = nullptr;
Type* type = DeclRefType::create(astBuilder, breadcrumb.declRef);
_lookUpMembersInType(astBuilder, name, type, request, result, &breadcrumb);
}
// We need to skip looking up in the interface decl itself, since we are
// looking up in the implicit `this` type.
for (; scope && !as<InterfaceDecl>(scope->containerDecl); scope = scope->parent)
{
// We need to skip looking up in the interface decl itself, since we are
// looking up in the implicit `this` type.
}
break;
}
// Before we proceed up to the next outer scope to perform lookup
// again, we need to consider what the current scope tells us
// about how to interpret uses of implicit `this` or `This`. For
// example, if we are inside a `[mutating]` method, then the implicit
// `this` that we use for lookup should be an l-value.
//
// Similarly, if we look up a member in a type from the scope
// of some nested type, then there shouldn't be an implicit `this`
// expression for the outer type, but instead an implicit `This`.
//
if (containerDeclRef.is<ConstructorDecl>())
{
// In the context of an `__init` declaration, the members of
// the surrounding type are accessible through a mutable `this`.
//
thisParameterMode = LookupResultItem::Breadcrumb::ThisParameterMode::MutableValue;
}
else if (containerDeclRef.is<SetterDecl>())
{
// In the context of a `set` accessor, the members of the
// surrounding type are accessible through a mutable `this`.
//
// TODO: At some point we may want a way to opt out of this
// behavior; it is possible to have a setter on a `struct`
// that actually just sets data into a buffer that is
// referenced by one of the `struct`'s fields.
//
thisParameterMode = LookupResultItem::Breadcrumb::ThisParameterMode::MutableValue;
}
else if (auto funcDeclRef = containerDeclRef.as<FunctionDeclBase>())
{
// The implicit `this`/`This` for a function-like declaration
// depends on modifiers attached to the declaration.
//
if (isEffectivelyStatic(funcDeclRef.getDecl()))
{
// A `static` method only has access to an implicit `This`,
// and does not have a `this` expression available.
//
thisParameterMode = LookupResultItem::Breadcrumb::ThisParameterMode::Type;
}
else if (funcDeclRef.getDecl()->hasModifier<MutatingAttribute>())
{
// In a non-`static` method marked `[mutating]` there is
// an implicit `this` parameter that is mutable.
//
thisParameterMode =
LookupResultItem::Breadcrumb::ThisParameterMode::MutableValue;
}
else if (funcDeclRef.getDecl()->hasModifier<RefAttribute>())
{
// In a non-`static` method marked `[ref]` there is
// an implicit `this` parameter that is mutable.
//
thisParameterMode =
LookupResultItem::Breadcrumb::ThisParameterMode::MutableValue;
}
else
{
// In all other cases, there is an implicit `this` parameter
// that is immutable.
//
thisParameterMode =
LookupResultItem::Breadcrumb::ThisParameterMode::ImmutableValue;
}
}
else if (containerDeclRef.as<AggTypeDeclBase>())
{
// When lookup moves from a nested typed declaration to an
// outer scope, there is no ability to use an implicit `this`
// expression, and we have only the `This` type available.
//
thisParameterMode = LookupResultItem::Breadcrumb::ThisParameterMode::Type;
}
}
if (result.isValid())
{
// If it's overloaded or the decl we have is of an overloadable type, or if we are
// looking up for completion suggestions then we just keep going
if (result.isOverloaded() || _isDeclOverloadable(result.item.declRef.getDecl()) ||
((int32_t)request.options & (int32_t)LookupOptions::Completion) != 0)
{
continue;
}
// If we've found a result in this scope (and it's not overloadable), then there
// is no reason to look further up (for now).
break;
}
}
// If we run out of scopes, then we are done.
}
LookupResult lookUp(
ASTBuilder* astBuilder,
SemanticsVisitor* semantics,
Name* name,
Scope* scope,
LookupMask mask,
bool considerAllLocalNamesInScope,
Decl* declToExclude,
bool ignoreTransparentMembers)
{
LookupResult result;
const auto options =
(LookupOptions)((int)(considerAllLocalNamesInScope
? LookupOptions::ConsiderAllLocalNamesInScope
: LookupOptions::None) |
(int)(ignoreTransparentMembers ? LookupOptions::IgnoreTransparentMembers
: LookupOptions::None));
LookupRequest request = initLookupRequest(semantics, name, mask, options, scope, declToExclude);
_lookUpInScopes(astBuilder, name, request, result);
return result;
}
LookupResult lookUpMember(
ASTBuilder* astBuilder,
SemanticsVisitor* semantics,
Name* name,
Type* type,
Scope* sourceScope,
LookupMask mask,
LookupOptions options)
{
LookupResult result;
LookupRequest request = initLookupRequest(semantics, name, mask, options, sourceScope, nullptr);
_lookUpMembersInType(astBuilder, name, type, request, result, nullptr);
return result;
}
} // namespace Slang
|