summaryrefslogtreecommitdiff
path: root/source/slang/slang-check-impl.h
blob: bd2392c67d73de7f93dd8394ea031a4f4c42928b (plain)
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
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
// slang-check-impl.h
#pragma once

// This file provides the private interfaces used by
// the various `slang-check-*` files that provide
// the semantic checking infrastructure.

#include "slang-check.h"
#include "slang-compiler.h"
#include "slang-visitor.h"

namespace Slang
{
    
        /// Should the given `decl` be treated as a static rather than instance declaration?
    bool isEffectivelyStatic(
        Decl*           decl);

    Type* checkProperType(
        Linkage*        linkage,
        TypeExp         typeExp,
        DiagnosticSink* sink);

    // A flat representation of basic types (scalars, vectors and matrices)
    // that can be used as lookup key in caches
    enum class BasicTypeKey : uint16_t
    {
        Invalid = 0xffff,                 ///< Value that can never be a valid type
    };

    SLANG_FORCE_INLINE BasicTypeKey makeBasicTypeKey(BaseType baseType, IntegerLiteralValue dim1 = 0, IntegerLiteralValue dim2 = 0)
    {
        SLANG_ASSERT(dim1 >= 0 && dim2 >= 0);
        return BasicTypeKey((uint8_t(baseType) << 8) | (uint8_t(dim1) << 4) | uint8_t(dim2));
    }

    inline BasicTypeKey makeBasicTypeKey(Type* typeIn)
    {
        if (auto basicType = as<BasicExpressionType>(typeIn))
        {
            return makeBasicTypeKey(basicType->baseType);
        }
        else if (auto vectorType = as<VectorExpressionType>(typeIn))
        {
            if (auto elemCount = as<ConstantIntVal>(vectorType->elementCount))
            {
                if( auto elemBasicType = as<BasicExpressionType>(vectorType->elementType) )
                {
                    return makeBasicTypeKey(elemBasicType->baseType, elemCount->value);
                }
            }
        }
        else if (auto matrixType = as<MatrixExpressionType>(typeIn))
        {
            if (auto elemCount1 = as<ConstantIntVal>(matrixType->getRowCount()))
            {
                if (auto elemCount2 = as<ConstantIntVal>(matrixType->getColumnCount()))
                {
                    if( auto elemBasicType = as<BasicExpressionType>(matrixType->getElementType()) )
                    {
                        return makeBasicTypeKey(elemBasicType->baseType, elemCount1->value, elemCount2->value);
                    }
                }
            }
        }
        return BasicTypeKey::Invalid;
    }

    struct BasicTypeKeyPair
    {
        BasicTypeKey type1, type2;
        bool operator==(const BasicTypeKeyPair& rhs) const { return type1 == rhs.type1 && type2 == rhs.type2; }
        bool operator!=(const BasicTypeKeyPair& rhs) const { return !(*this == rhs); }

        bool isValid() const { return type1 != BasicTypeKey::Invalid && type2 != BasicTypeKey::Invalid; }

        HashCode getHashCode()
        {
            return HashCode(int(type1) << 16 | int(type2));
        }
    };

    struct OperatorOverloadCacheKey
    {
        intptr_t operatorName;
        BasicTypeKey args[2];
        bool operator == (OperatorOverloadCacheKey key)
        {
            return operatorName == key.operatorName && args[0] == key.args[0] && args[1] == key.args[1];
        }
        HashCode getHashCode()
        {
            return HashCode(((int)(UInt64)(void*)(operatorName) << 16) ^ (int(args[0]) << 8) ^ (int(args[1])));
        }
        bool fromOperatorExpr(OperatorExpr* opExpr)
        {
            // First, lets see if the argument types are ones
            // that we can encode in our space of keys.
            args[0] = BasicTypeKey::Invalid;
            args[1] = BasicTypeKey::Invalid;
            if (opExpr->arguments.getCount() > 2)
                return false;

            for (Index i = 0; i < opExpr->arguments.getCount(); i++)
            {
                auto key = makeBasicTypeKey(opExpr->arguments[i]->type.Ptr());
                if (key == BasicTypeKey::Invalid)
                {
                    return false;
                }
                args[i]=  key;
            }

            // Next, lets see if we can find an intrinsic opcode
            // attached to an overloaded definition (filtered for
            // definitions that could conceivably apply to us).
            //
            // TODO: This should really be parsed on the operator name
            // plus fixity, rather than the intrinsic opcode...
            //
            // We will need to reject postfix definitions for prefix
            // operators, and vice versa, to ensure things work.
            //
            auto prefixExpr = as<PrefixExpr>(opExpr);
            auto postfixExpr = as<PostfixExpr>(opExpr);

            if (auto overloadedBase = as<OverloadedExpr>(opExpr->functionExpr))
            {
                for(auto item : overloadedBase->lookupResult2 )
                {
                    // Look at a candidate definition to be called and
                    // see if it gives us a key to work with.
                    //
                    Decl* funcDecl = overloadedBase->lookupResult2.item.declRef.decl;
                    if (auto genDecl = as<GenericDecl>(funcDecl))
                        funcDecl = genDecl->inner;

                    // Reject definitions that have the wrong fixity.
                    //
                    if(prefixExpr && !funcDecl->findModifier<PrefixModifier>())
                        continue;
                    if(postfixExpr && !funcDecl->findModifier<PostfixModifier>())
                        continue;

                    if (auto intrinsicOp = funcDecl->findModifier<IntrinsicOpModifier>())
                    {
                        operatorName = intrinsicOp->op;
                        return true;
                    }
                }
            }
            return false;
        }
    };

    struct OverloadCandidate
    {
        enum class Flavor
        {
            Func,
            Generic,
            UnspecializedGeneric,
        };
        Flavor flavor;

        enum class Status
        {
            GenericArgumentInferenceFailed,
            Unchecked,
            ArityChecked,
            FixityChecked,
            TypeChecked,
            DirectionChecked,
            Applicable,
        };
        Status status = Status::Unchecked;

        // Reference to the declaration being applied
        LookupResultItem item;

        // The type of the result expression if this candidate is selected
        Type*	resultType = nullptr;

        // A system for tracking constraints introduced on generic parameters
        //            ConstraintSystem constraintSystem;

        // How much conversion cost should be considered for this overload,
        // when ranking candidates.
        ConversionCost conversionCostSum = kConversionCost_None;

        // When required, a candidate can store a pre-checked list of
        // arguments so that we don't have to repeat work across checking
        // phases. Currently this is only needed for generics.
        Substitutions*   subst = nullptr;
    };

    struct TypeCheckingCache
    {
        Dictionary<OperatorOverloadCacheKey, OverloadCandidate> resolvedOperatorOverloadCache;
        Dictionary<BasicTypeKeyPair, ConversionCost> conversionCostCache;
    };

        /// Shared state for a semantics-checking session.
    struct SharedSemanticsContext
    {
        Linkage*        m_linkage   = nullptr;

            /// The (optional) "primary" module that is the parent to everything that will be checked.
        Module*         m_module    = nullptr;

        DiagnosticSink* m_sink      = nullptr;

        DiagnosticSink* getSink()
        {
            return m_sink;
        }

        // We need to track what has been `import`ed into
        // the scope of this semantic checking session,
        // and also to avoid importing the same thing more
        // than once.
        //
        List<ModuleDecl*> importedModulesList;
        HashSet<ModuleDecl*> importedModulesSet;

    public:
        SharedSemanticsContext(
            Linkage*        linkage,
            Module*         module,
            DiagnosticSink* sink)
            : m_linkage(linkage)
            , m_module(module)
            , m_sink(sink)
        {}

        Session* getSession()
        {
            return m_linkage->getSessionImpl();
        }

        Linkage* getLinkage()
        {
            return m_linkage;
        }

        Module* getModule()
        {
            return m_module;
        }

            /// Get the list of extension declarations that appear to apply to `decl` in this context
        List<ExtensionDecl*> const& getCandidateExtensionsForTypeDecl(AggTypeDecl* decl);

            /// Register a candidate extension `extDecl` for `typeDecl` encountered during checking.
        void registerCandidateExtension(AggTypeDecl* typeDecl, ExtensionDecl* extDecl);

    private:
            /// Mapping from type declarations to the known extensiosn that apply to them
        Dictionary<AggTypeDecl*, RefPtr<CandidateExtensionList>> m_mapTypeDeclToCandidateExtensions;

            /// Is the `m_mapTypeDeclToCandidateExtensions` dictionary valid and up to date?
        bool m_candidateExtensionListsBuilt = false;

            /// Add candidate extensions declared in `moduleDecl` to `m_mapTypeDeclToCandidateExtensions`
        void _addCandidateExtensionsFromModule(ModuleDecl* moduleDecl);
    };

    struct SemanticsVisitor
    {
        SemanticsVisitor(
            SharedSemanticsContext* shared)
            : m_shared(shared),
            m_astBuilder(shared->getLinkage()->getASTBuilder())
        {}

        SharedSemanticsContext* m_shared = nullptr;
        ASTBuilder* m_astBuilder = nullptr;

        SharedSemanticsContext* getShared() { return m_shared; }
        ASTBuilder* getASTBuilder() { return m_astBuilder;}

        DiagnosticSink* getSink() { return m_shared->getSink(); }

        Session* getSession() { return m_shared->getSession(); }

        Linkage* getLinkage() { return m_shared->m_linkage; }
        NamePool* getNamePool() { return getLinkage()->getNamePool(); }

            /// Information for tracking one or more outer statements.
            ///
            /// During checking of statements, we need to track what
            /// outer statements are in scope, so that we can resolve
            /// the target for a `break` or `continue` statement (and
            /// validate that such statements are only used in contexts
            /// where such a target exists).
            ///
            /// We use a linked list of `OuterStmtInfo` threaded up
            /// through the recursive call stack to track the statements
            /// that are lexically surrounding the one we are checking.
            ///
        struct OuterStmtInfo
        {
            Stmt*           stmt = nullptr;
            OuterStmtInfo*  next;
        };

    public:
        // Translate Types


        Expr* TranslateTypeNodeImpl(Expr* node);
        Type* ExtractTypeFromTypeRepr(Expr* typeRepr);
        Type* TranslateTypeNode(Expr* node);
        TypeExp TranslateTypeNodeForced(TypeExp const& typeExp);
        TypeExp TranslateTypeNode(TypeExp const& typeExp);

        DeclRefType* getExprDeclRefType(Expr * expr);

            /// Is `decl` usable as a static member?
        bool isDeclUsableAsStaticMember(
            Decl*   decl);

            /// Is `item` usable as a static member?
        bool isUsableAsStaticMember(
            LookupResultItem const& item);

            /// Move `expr` into a temporary variable and execute `func` on that variable.
            ///
            /// Returns an expression that wraps both the creation and initialization of
            /// the temporary, and the computation created by `func`.
            ///
        template<typename F>
        Expr* moveTemp(Expr* const& expr, F const& func);

            /// Execute `func` on a variable with the value of `expr`.
            ///
            /// If `expr` is just a reference to an immutable (e.g., `let`) variable
            /// then this might use the existing variable. Otherwise it will create
            /// a new variable to hold `expr`, using `moveTemp()`.
            ///
        template<typename F>
        Expr* maybeMoveTemp(Expr* const& expr, F const& func);

            /// Return an expression that represents "opening" the existential `expr`.
            ///
            /// The type of `expr` must be an interface type, matching `interfaceDeclRef`.
            ///
            /// If we scope down the PL theory to just the case that Slang cares about,
            /// a value of an existential type like `IMover` is a tuple of:
            ///
            ///  * a concrete type `X`
            ///  * a witness `w` of the fact that `X` implements `IMover`
            ///  * a value `v` of type `X`
            ///
            /// "Opening" an existential value is the process of decomposing a single
            /// value `e : IMover` into the pieces `X`, `w`, and `v`.
            ///
            /// Rather than return all those pieces individually, this operation
            /// returns an expression that logically corresponds to `v`: an expression
            /// of type `X`, where the type carries the knowledge that `X` implements `IMover`.
            ///
        Expr* openExistential(
            Expr*            expr,
            DeclRef<InterfaceDecl>  interfaceDeclRef);

            /// If `expr` has existential type, then open it.
            ///
            /// Returns an expression that opens `expr` if it had existential type.
            /// Otherwise returns `expr` itself.
            ///
            /// See `openExistential` for a discussion of what "opening" an
            /// existential-type value means.
            ///
        Expr* maybeOpenExistential(Expr* expr);

        Expr* ConstructDeclRefExpr(
            DeclRef<Decl>   declRef,
            Expr*    baseExpr,
            SourceLoc       loc);

        Expr* ConstructDerefExpr(
            Expr*    base,
            SourceLoc       loc);

        Expr* ConstructLookupResultExpr(
            LookupResultItem const& item,
            Expr*            baseExpr,
            SourceLoc               loc);

        Expr* createLookupResultExpr(
            Name*                   name,
            LookupResult const&     lookupResult,
            Expr*            baseExpr,
            SourceLoc               loc);

            /// Attempt to "resolve" an overloaded `LookupResult` to only include the "best" results
        LookupResult resolveOverloadedLookup(LookupResult const& lookupResult);

            /// Attempt to resolve `expr` into an expression that refers to a single declaration/value.
            /// If `expr` isn't overloaded, then it will be returned as-is.
            ///
            /// The provided `mask` is used to filter items down to those that are applicable in a given context (e.g., just types).
            ///
            /// If the expression cannot be resolved to a single value then *if* `diagSink` is non-null an
            /// appropriate "ambiguous reference" error will be reported, and an error expression will be returned.
            /// Otherwise, the original expression is returned if resolution fails.
            ///
        Expr* maybeResolveOverloadedExpr(Expr* expr, LookupMask mask, DiagnosticSink* diagSink);

            /// Attempt to resolve `overloadedExpr` into an expression that refers to a single declaration/value.
            ///
            /// Equivalent to `maybeResolveOverloadedExpr` with `diagSink` bound to the sink for the `SemanticsVisitor`.
        Expr* resolveOverloadedExpr(OverloadedExpr* overloadedExpr, LookupMask mask);

            /// Worker reoutine for `maybeResolveOverloadedExpr` and `resolveOverloadedExpr`.
        Expr* _resolveOverloadedExprImpl(OverloadedExpr* overloadedExpr, LookupMask mask, DiagnosticSink* diagSink);

        void diagnoseAmbiguousReference(OverloadedExpr* overloadedExpr, LookupResult const& lookupResult);
        void diagnoseAmbiguousReference(Expr* overloadedExpr);


        Expr* ExpectATypeRepr(Expr* expr);

        Type* ExpectAType(Expr* expr);

        Type* ExtractGenericArgType(Expr* exp);

        IntVal* ExtractGenericArgInteger(Expr* exp, DiagnosticSink* sink);
        IntVal* ExtractGenericArgInteger(Expr* exp);

        Val* ExtractGenericArgVal(Expr* exp);

        // Construct a type representing the instantiation of
        // the given generic declaration for the given arguments.
        // The arguments should already be checked against
        // the declaration.
        Type* InstantiateGenericType(
            DeclRef<GenericDecl>        genericDeclRef,
            List<Expr*> const&   args);

        // These routines are bottlenecks for semantic checking,
        // so that we can add some quality-of-life features for users
        // in cases where the compiler crashes
        //
        void dispatchStmt(Stmt* stmt, FunctionDeclBase* parentFunc, OuterStmtInfo* outerStmts);
        void dispatchExpr(Expr* expr);

            /// Ensure that a declaration has been checked up to some state
            /// (aka, a phase of semantic checking) so that we can safely
            /// perform certain operations on it.
            ///
            /// Calling `ensureDecl` may cause the type-checker to recursively
            /// start checking `decl` on top of the stack that is already
            /// doing other semantic checking. Care should be taken when relying
            /// on this function to avoid blowing out the stack or (even worse
            /// creating a circular dependency).
            ///
        void ensureDecl(Decl* decl, DeclCheckState state);

            /// Helper routine allowing `ensureDecl` to be called on a `DeclRef`
        void ensureDecl(DeclRefBase const& declRef, DeclCheckState state)
        {
            ensureDecl(declRef.getDecl(), state);
        }

            /// Helper routine allowing `ensureDecl` to be used on a `DeclBase`
            ///
            /// `DeclBase` is the base clas of `Decl` and `DeclGroup`. When
            /// called on a `DeclGroup` this function just calls `ensureDecl()`
            /// on each declaration in the group.
            ///
        void ensureDeclBase(DeclBase* decl, DeclCheckState state);

        // A "proper" type is one that can be used as the type of an expression.
        // Put simply, it can be a concrete type like `int`, or a generic
        // type that is applied to arguments, like `Texture2D<float4>`.
        // The type `void` is also a proper type, since we can have expressions
        // that return a `void` result (e.g., many function calls).
        //
        // A "non-proper" type is any type that can't actually have values.
        // A simple example of this in C++ is `std::vector` - you can't have
        // a value of this type.
        //
        // Part of what this function does is give errors if somebody tries
        // to use a non-proper type as the type of a variable (or anything
        // else that needs a proper type).
        //
        // The other thing it handles is the fact that HLSL lets you use
        // the name of a non-proper type, and then have the compiler fill
        // in the default values for its type arguments (e.g., a variable
        // given type `Texture2D` will actually have type `Texture2D<float4>`).
        bool CoerceToProperTypeImpl(
            TypeExp const&  typeExp,
            Type**   outProperType,
            DiagnosticSink* diagSink);

        TypeExp CoerceToProperType(TypeExp const& typeExp);

        TypeExp tryCoerceToProperType(TypeExp const& typeExp);

        // Check a type, and coerce it to be proper
        TypeExp CheckProperType(TypeExp typeExp);

        // For our purposes, a "usable" type is one that can be
        // used to declare a function parameter, variable, etc.
        // These turn out to be all the proper types except
        // `void`.
        //
        // TODO(tfoley): consider just allowing `void` as a
        // simple example of a "unit" type, and get rid of
        // this check.
        TypeExp CoerceToUsableType(TypeExp const& typeExp);

        // Check a type, and coerce it to be usable
        TypeExp CheckUsableType(TypeExp typeExp);

        Expr* CheckTerm(Expr* term);

        Expr* CreateErrorExpr(Expr* expr);

        bool IsErrorExpr(Expr* expr);

        // Capture the "base" expression in case this is a member reference
        Expr* GetBaseExpr(Expr* expr);

            /// Validate a declaration to ensure that it doesn't introduce a circularly-defined constant
            ///
            /// Circular definition in a constant may lead to infinite looping or stack overflow in
            /// the compiler, so it needs to be protected against.
            ///
            /// Note that this function does *not* protect against circular definitions in general,
            /// and a program that indirectly initializes a global variable using its own value (e.g.,
            /// by calling a function that indirectly reads the variable) will be allowed and then
            /// exhibit undefined behavior at runtime.
            ///
        void _validateCircularVarDefinition(VarDeclBase* varDecl);

    public:

        bool ValuesAreEqual(
            IntVal* left,
            IntVal* right);

        // Compute the cost of using a particular declaration to
        // perform implicit type conversion.
        ConversionCost getImplicitConversionCost(
            Decl* decl);

        bool isEffectivelyScalarForInitializerLists(
            Type*    type);

            /// Should the provided expression (from an initializer list) be used directly to initialize `toType`?
        bool shouldUseInitializerDirectly(
            Type*    toType,
            Expr*    fromExpr);

            /// Read a value from an initializer list expression.
            ///
            /// This reads one or more argument from the initializer list
            /// given as `fromInitializerListExpr` to initialize a value
            /// of type `toType`. This may involve reading one or
            /// more arguments from the initializer list, depending
            /// on whether `toType` is an aggregate or not, and on
            /// whether the next argument in the initializer list is
            /// itself an initializer list.
            ///
            /// This routine returns `true` if it was able to read
            /// arguments that can form a value of type `toType`,
            /// and `false` otherwise.
            ///
            /// If the routine succeeds and `outToExpr` is non-null,
            /// then it will be filled in with an expression
            /// representing the value (or type `toType`) that was read,
            /// or it will be left null to indicate that a default
            /// value should be used.
            ///
            /// If the routine fails and `outToExpr` is non-null,
            /// then a suitable diagnostic will be emitted.
            ///
        bool _readValueFromInitializerList(
            Type*                toType,
            Expr**               outToExpr,
            InitializerListExpr* fromInitializerListExpr,
            UInt                       &ioInitArgIndex);

            /// Read an aggregate value from an initializer list expression.
            ///
            /// This reads one or more arguments from the initializer list
            /// given as `fromInitializerListExpr` to initialize the
            /// fields/elements of a value of type `toType`.
            ///
            /// This routine returns `true` if it was able to read
            /// arguments that can form a value of type `toType`,
            /// and `false` otherwise.
            ///
            /// If the routine succeeds and `outToExpr` is non-null,
            /// then it will be filled in with an expression
            /// representing the value (or type `toType`) that was read,
            /// or it will be left null to indicate that a default
            /// value should be used.
            ///
            /// If the routine fails and `outToExpr` is non-null,
            /// then a suitable diagnostic will be emitted.
            ///
        bool _readAggregateValueFromInitializerList(
            Type*                inToType,
            Expr**               outToExpr,
            InitializerListExpr* fromInitializerListExpr,
            UInt                       &ioArgIndex);

            /// Coerce an initializer-list expression to a specific type.
            ///
            /// This reads one or more arguments from the initializer list
            /// given as `fromInitializerListExpr` to initialize the
            /// fields/elements of a value of type `toType`.
            ///
            /// This routine returns `true` if it was able to read
            /// arguments that can form a value of type `toType`,
            /// with no arguments left over, and `false` otherwise.
            ///
            /// If the routine succeeds and `outToExpr` is non-null,
            /// then it will be filled in with an expression
            /// representing the value (or type `toType`) that was read,
            /// or it will be left null to indicate that a default
            /// value should be used.
            ///
            /// If the routine fails and `outToExpr` is non-null,
            /// then a suitable diagnostic will be emitted.
            ///
        bool _coerceInitializerList(
            Type*                toType,
            Expr**               outToExpr,
            InitializerListExpr* fromInitializerListExpr);

            /// Report that implicit type coercion is not possible.
        bool _failedCoercion(
            Type*    toType,
            Expr**   outToExpr,
            Expr*    fromExpr);

            /// Central engine for implementing implicit coercion logic
            ///
            /// This function tries to find an implicit conversion path from
            /// `fromType` to `toType`. It returns `true` if a conversion
            /// is found, and `false` if not.
            ///
            /// If a conversion is found, then its cost will be written to `outCost`.
            ///
            /// If a `fromExpr` is provided, it must be of type `fromType`,
            /// and represent a value to be converted.
            ///
            /// If `outToExpr` is non-null, and if a conversion is found, then
            /// `*outToExpr` will be set to an expression that performs the
            /// implicit conversion of `fromExpr` (which must be non-null
            /// to `toType`).
            ///
            /// The case where `outToExpr` is non-null is used to identify
            /// when a conversion is being done "for real" so that diagnostics
            /// should be emitted on failure.
            ///
        bool _coerce(
            Type*    toType,
            Expr**   outToExpr,
            Type*    fromType,
            Expr*    fromExpr,
            ConversionCost* outCost);

            /// Check whether implicit type coercion from `fromType` to `toType` is possible.
            ///
            /// If conversion is possible, returns `true` and sets `outCost` to the cost
            /// of the conversion found (if `outCost` is non-null).
            ///
            /// If conversion is not possible, returns `false`.
            ///
        bool canCoerce(
            Type*    toType,
            Type*    fromType,
            Expr*    fromExpr,
            ConversionCost* outCost = 0);

        TypeCastExpr* createImplicitCastExpr();

        Expr* CreateImplicitCastExpr(
            Type*	toType,
            Expr*	fromExpr);

            /// Create an "up-cast" from a value to an interface type
            ///
            /// This operation logically constructs an "existential" value,
            /// which packages up the value, its type, and the witness
            /// of its conformance to the interface.
            ///
        Expr* createCastToInterfaceExpr(
            Type*    toType,
            Expr*    fromExpr,
            Val*     witness);

            /// Implicitly coerce `fromExpr` to `toType` and diagnose errors if it isn't possible
        Expr* coerce(
            Type*    toType,
            Expr*    fromExpr);

        // Fill in default substitutions for the 'subtype' part of a type constraint decl
        void CheckConstraintSubType(TypeExp& typeExp);

        void checkGenericDeclHeader(GenericDecl* genericDecl);

        ConstantIntVal* checkConstantIntVal(
            Expr*    expr);

        ConstantIntVal* checkConstantEnumVal(
            Expr*    expr);

        // Check an expression, coerce it to the `String` type, and then
        // ensure that it has a literal (not just compile-time constant) value.
        bool checkLiteralStringVal(
            Expr*    expr,
            String*         outVal);

        void visitModifier(Modifier*);

        AttributeDecl* lookUpAttributeDecl(Name* attributeName, Scope* scope);

        bool hasIntArgs(Attribute* attr, int numArgs);
        bool hasStringArgs(Attribute* attr, int numArgs);

        bool getAttributeTargetSyntaxClasses(SyntaxClass<NodeBase> & cls, uint32_t typeFlags);

        bool validateAttribute(Attribute* attr, AttributeDecl* attribClassDecl);

        AttributeBase* checkAttribute(
            UncheckedAttribute*     uncheckedAttr,
            ModifiableSyntaxNode*   attrTarget);

        Modifier* checkModifier(
            Modifier*        m,
            ModifiableSyntaxNode*   syntaxNode);

        void checkModifiers(ModifiableSyntaxNode* syntaxNode);

        bool doesSignatureMatchRequirement(
            DeclRef<CallableDecl>   satisfyingMemberDeclRef,
            DeclRef<CallableDecl>   requiredMemberDeclRef,
            RefPtr<WitnessTable>    witnessTable);

        bool doesAccessorMatchRequirement(
            DeclRef<AccessorDecl>   satisfyingMemberDeclRef,
            DeclRef<AccessorDecl>   requiredMemberDeclRef);

        bool doesPropertyMatchRequirement(
            DeclRef<PropertyDecl>   satisfyingMemberDeclRef,
            DeclRef<PropertyDecl>   requiredMemberDeclRef,
            RefPtr<WitnessTable>    witnessTable);

        bool doesGenericSignatureMatchRequirement(
            DeclRef<GenericDecl>        genDecl,
            DeclRef<GenericDecl>        requirementGenDecl,
            RefPtr<WitnessTable>        witnessTable);

        bool doesTypeSatisfyAssociatedTypeRequirement(
            Type*            satisfyingType,
            DeclRef<AssocTypeDecl>  requiredAssociatedTypeDeclRef,
            RefPtr<WitnessTable>    witnessTable);

        // Does the given `memberDecl` work as an implementation
        // to satisfy the requirement `requiredMemberDeclRef`
        // from an interface?
        //
        // If it does, then inserts a witness into `witnessTable`
        // and returns `true`, otherwise returns `false`
        bool doesMemberSatisfyRequirement(
            DeclRef<Decl>               memberDeclRef,
            DeclRef<Decl>               requiredMemberDeclRef,
            RefPtr<WitnessTable>        witnessTable);

        // State used while checking if a declaration (either a type declaration
        // or an extension of that type) conforms to the interfaces it claims
        // via its inheritance clauses.
        //
        struct ConformanceCheckingContext
        {
                /// The type for which conformances are being checked
            Type*           conformingType;

                /// The outer declaration for the conformances being checked (either a type or `extension` declaration)
            ContainerDecl*  parentDecl;

            Dictionary<DeclRef<InterfaceDecl>, RefPtr<WitnessTable>>    mapInterfaceToWitnessTable;
        };

            /// Attempt to synthesize a method that can satisfy `requiredMemberDeclRef` using `lookupResult`.
            ///
            /// On success, installs the syntethesized method in `witnessTable` and returns `true`.
            /// Otherwise, returns `false`.
        bool trySynthesizeMethodRequirementWitness(
            ConformanceCheckingContext* context,
            LookupResult const&         lookupResult,
            DeclRef<FuncDecl>           requiredMemberDeclRef,
            RefPtr<WitnessTable>        witnessTable);

            /// Attempt to synthesize a property that can satisfy `requiredMemberDeclRef` using `lookupResult`.
            ///
            /// On success, installs the syntethesized method in `witnessTable` and returns `true`.
            /// Otherwise, returns `false`.
            ///
        bool trySynthesizePropertyRequirementWitness(
            ConformanceCheckingContext* context,
            LookupResult const&         lookupResult,
            DeclRef<PropertyDecl>       requiredMemberDeclRef,
            RefPtr<WitnessTable>        witnessTable);

            /// Attempt to synthesize a declartion that can satisfy `requiredMemberDeclRef` using `lookupResult`.
            ///
            /// On success, installs the syntethesized declaration in `witnessTable` and returns `true`.
            /// Otherwise, returns `false`.
        bool trySynthesizeRequirementWitness(
            ConformanceCheckingContext* context,
            LookupResult const&         lookupResult,
            DeclRef<Decl>               requiredMemberDeclRef,
            RefPtr<WitnessTable>        witnessTable);

        // Find the appropriate member of a declared type to
        // satisfy a requirement of an interface the type
        // claims to conform to.
        //
        // The type declaration `typeDecl` has declared that it
        // conforms to the interface `interfaceDeclRef`, and
        // `requiredMemberDeclRef` is a required member of
        // the interface.
        //
        // If a satisfying value is found, registers it in
        // `witnessTable` and returns `true`, otherwise
        // returns `false`.
        //
        bool findWitnessForInterfaceRequirement(
            ConformanceCheckingContext* context,
            Type*                       subType,
            Type*                       superInterfaceType,
            InheritanceDecl*            inheritanceDecl,
            DeclRef<InterfaceDecl>      superInterfaceDeclRef,
            DeclRef<Decl>               requiredMemberDeclRef,
            RefPtr<WitnessTable>        witnessTable,
            SubtypeWitness*             subTypeConformsToSuperInterfaceWitness);

        // Check that the type declaration `typeDecl`, which
        // declares conformance to the interface `interfaceDeclRef`,
        // (via the given `inheritanceDecl`) actually provides
        // members to satisfy all the requirements in the interface.
        bool checkInterfaceConformance(
            ConformanceCheckingContext* context,
            Type*                       subType,
            Type*                       superInterfaceType,
            InheritanceDecl*            inheritanceDecl,
            DeclRef<InterfaceDecl>      superInterfaceDeclRef,
            SubtypeWitness*             subTypeConformsToSuperInterfaceWitness,
            WitnessTable*               witnessTable);

        RefPtr<WitnessTable> checkInterfaceConformance(
            ConformanceCheckingContext* context,
            Type*                       subType,
            Type*                       superInterfaceType,
            InheritanceDecl*            inheritanceDecl,
            DeclRef<InterfaceDecl>      superInterfaceDeclRef,
            SubtypeWitness*             subTypeConformsToSuperInterfaceWitness);

        bool checkConformanceToType(
            ConformanceCheckingContext* context,
            Type*                       subType,
            InheritanceDecl*            inheritanceDecl,
            Type*                       superType,
            SubtypeWitness*             subIsSuperWitness,
            WitnessTable*               witnessTable);

            /// Check that `type` which has declared that it inherits from (and/or implements)
            /// another type via `inheritanceDecl` actually does what it needs to for that
            /// inheritance to be valid.
        bool checkConformance(
            Type*                       type,
            InheritanceDecl*            inheritanceDecl,
            ContainerDecl*              parentDecl);

        void checkExtensionConformance(ExtensionDecl* decl);

        void checkAggTypeConformance(AggTypeDecl* decl);

        bool isIntegerBaseType(BaseType baseType);

            /// Is `type` a scalar integer type.
        bool isScalarIntegerType(Type* type);

        // Validate that `type` is a suitable type to use
        // as the tag type for an `enum`
        void validateEnumTagType(Type* type, SourceLoc const& loc);

        void checkStmt(Stmt* stmt, FunctionDeclBase* outerFunction, OuterStmtInfo* outerStmts);

        void getGenericParams(
            GenericDecl*                        decl,
            List<Decl*>&                        outParams,
            List<GenericTypeConstraintDecl*>&   outConstraints);

            /// Determine if `left` and `right` have matching generic signatures.
            /// If they do, then outputs a substitution to `ioSubstRightToLeft` that
            /// can be used to specialize `right` to the parameters of `left`.
        bool doGenericSignaturesMatch(
            GenericDecl*                    left,
            GenericDecl*                    right,
            GenericSubstitution**    outSubstRightToLeft);

        // Check if two functions have the same signature for the purposes
        // of overload resolution.
        bool doFunctionSignaturesMatch(
            DeclRef<FuncDecl> fst,
            DeclRef<FuncDecl> snd);

        GenericSubstitution* createDummySubstitutions(
            GenericDecl* genericDecl);

        Result checkRedeclaration(Decl* newDecl, Decl* oldDecl);
        Result checkFuncRedeclaration(FuncDecl* newDecl, FuncDecl* oldDecl);
        void checkForRedeclaration(Decl* decl);

        Expr* checkPredicateExpr(Expr* expr);

        Expr* checkExpressionAndExpectIntegerConstant(Expr* expr, IntVal** outIntVal);

        IntegerLiteralValue GetMinBound(IntVal* val);

        void maybeInferArraySizeForVariable(VarDeclBase* varDecl);

        void validateArraySizeForVariable(VarDeclBase* varDecl);

        IntVal* getIntVal(IntegerLiteralExpr* expr);

        inline IntVal* getIntVal(SubstExpr<IntegerLiteralExpr> expr)
        {
            return getIntVal(expr.getExpr());
        }

        Name* getName(String const& text)
        {
            return getNamePool()->getName(text);
        }

            /// Helper type to detect and catch circular definitions when folding constants,
            /// to prevent the compiler from going into infinite loops or overflowing the stack.
        struct ConstantFoldingCircularityInfo
        {
            ConstantFoldingCircularityInfo(
                Decl*                           decl,
                ConstantFoldingCircularityInfo* next)
                : decl(decl)
                , next(next)
            {}

                /// A declaration whose value is contributing to the constant being folded
            Decl*                           decl = nullptr;

                /// The rest of the links in the chain of declarations being folded
            ConstantFoldingCircularityInfo* next = nullptr;
        };

            /// Try to apply front-end constant folding to determine the value of `invokeExpr`.
        IntVal* tryConstantFoldExpr(
            SubstExpr<InvokeExpr>           invokeExpr,
            ConstantFoldingCircularityInfo* circularityInfo);

            /// Try to apply front-end constant folding to determine the value of `expr`.
        IntVal* tryConstantFoldExpr(
            SubstExpr<Expr>                 expr,
            ConstantFoldingCircularityInfo* circularityInfo);

        bool _checkForCircularityInConstantFolding(
            Decl*                           decl,
            ConstantFoldingCircularityInfo* circularityInfo);

            /// Try to resolve a compile-time constant `IntVal` from the given `declRef`.
        IntVal* tryConstantFoldDeclRef(
            DeclRef<VarDeclBase> const&     declRef,
            ConstantFoldingCircularityInfo* circularityInfo);

            /// Try to extract the value of an integer constant expression, either
            /// returning the `IntVal` value, or null if the expression isn't recognized
            /// as an integer constant.
            ///
        IntVal* tryFoldIntegerConstantExpression(
            SubstExpr<Expr>                 expr,
            ConstantFoldingCircularityInfo* circularityInfo);

        // Enforce that an expression resolves to an integer constant, and get its value
        IntVal* CheckIntegerConstantExpression(Expr* inExpr);
        IntVal* CheckIntegerConstantExpression(Expr* inExpr, DiagnosticSink* sink);

        IntVal* CheckEnumConstantExpression(Expr* expr);


        Expr* CheckSimpleSubscriptExpr(
            IndexExpr*   subscriptExpr,
            Type*              elementType);

        // The way that we have designed out type system, pretyt much *every*
        // type is a reference to some declaration in the standard library.
        // That means that when we construct a new type on the fly, we need
        // to make sure that it is wired up to reference the appropriate
        // declaration, or else it won't compare as equal to other types
        // that *do* reference the declaration.
        //
        // This function is used to construct a `vector<T,N>` type
        // programmatically, so that it will work just like a type of
        // that form constructed by the user.
        VectorExpressionType* createVectorType(
            Type*  elementType,
            IntVal*          elementCount);

        //

            /// Given an immutable `expr` used as an l-value emit a special diagnostic if it was derived from `this`.
        void maybeDiagnoseThisNotLValue(Expr* expr);

        void registerExtension(ExtensionDecl* decl);

        // Figure out what type an initializer/constructor declaration
        // is supposed to return. In most cases this is just the type
        // declaration that its declaration is nested inside.
        Type* findResultTypeForConstructorDecl(ConstructorDecl* decl);

            /// Determine what type `This` should refer to in the context of the given parent `decl`.
        Type* calcThisType(DeclRef<Decl> decl);

            /// Determine what type `This` should refer to in an extension of `type`.
        Type* calcThisType(Type* type);


        //

        struct Constraint
        {
            Decl*		decl = nullptr; // the declaration of the thing being constraints
            Val*	val = nullptr; // the value to which we are constraining it
            bool satisfied = false; // Has this constraint been met?
        };

        // A collection of constraints that will need to be satisfied (solved)
        // in order for checking to succeed.
        struct ConstraintSystem
        {
            // A source location to use in reporting any issues
            SourceLoc loc;

            // The generic declaration whose parameters we
            // are trying to solve for.
            GenericDecl* genericDecl = nullptr;

            // Constraints we have accumulated, which constrain
            // the possible arguments for those parameters.
            List<Constraint> constraints;
        };

        Type* TryJoinVectorAndScalarType(
            VectorExpressionType* vectorType,
            BasicExpressionType*  scalarType);

        struct TypeWitnessBreadcrumb
        {
            TypeWitnessBreadcrumb*  prev;

            Type*            sub = nullptr;
            Type*            sup = nullptr;
            DeclRef<Decl>           declRef;
        };

            // Create a subtype witness based on the declared relationship
            // found in a single breadcrumb
        DeclaredSubtypeWitness* createSimpleSubtypeWitness(
            TypeWitnessBreadcrumb*  breadcrumb);

            /// Create a witness that `subType` is a sub-type of `superTypeDeclRef`.
            ///
            /// The `inBreadcrumbs` parameter represents a linked list of steps
            /// in the process that validated the sub-type relationship, which
            /// will be used to inform the construction of the witness.
            ///
        Val* createTypeWitness(
            Type*            subType,
            DeclRef<AggTypeDecl>  superTypeDeclRef,
            TypeWitnessBreadcrumb*  inBreadcrumbs);
    
            /// Is the given interface one that a tagged-union type can conform to?
            ///
            /// If a tagged union type `__TaggedUnion(A,B)` is going to be
            /// plugged in for a type parameter `T : IFoo` then we need to
            /// be sure that the interface `IFoo` doesn't have anything
            /// that could lead to unsafe/unsound behavior. This function
            /// checks that all the requirements on the interfaceare safe ones.
            ///
        bool isInterfaceSafeForTaggedUnion(
            DeclRef<InterfaceDecl> interfaceDeclRef);

            /// Is the given interface requirement one that a tagged-union type can satisfy?
            ///
            /// Unsafe requirements include any `static` requirements,
            /// any associated types, and also any requirements that make
            /// use of the `This` type (once we support it).
            ///
        bool isInterfaceRequirementSafeForTaggedUnion(
            DeclRef<InterfaceDecl>  interfaceDeclRef,
            DeclRef<Decl>           requirementDeclRef);

            /// Check whether `subType` is declared a sub-type of `superTypeDeclRef`
            ///
            /// If this function returns `true` (because the subtype relationship holds),
            /// then `outWitness` will be set to a value that serves as a witness
            /// to the subtype relationship.
            ///
            /// This function may be used to validate a transitive subtype relationship
            /// where, e.g., `A : C` becase `A : B` and `B : C`. In such a case, a recursive
            /// call to `_isDeclaredSubtype` may occur where `originalSubType` is `A`,
            /// `subType` is `C`, and `superTypeDeclRef` is `C`. The `inBreadcrumbs` in that
            /// case would include information for the `A : B` relationship, which can be
            /// used to construct a witness for `A : C` from the `A : B` and `B : C` witnesses.
            ///
        bool _isDeclaredSubtype(
            Type*            originalSubType,
            Type*            subType,
            DeclRef<AggTypeDecl>    superTypeDeclRef,
            Val**            outWitness,
            TypeWitnessBreadcrumb*  inBreadcrumbs);

            /// Check whether `subType` is a sub-type of `superTypeDeclRef`.
        bool isDeclaredSubtype(
            Type*            subType,
            DeclRef<AggTypeDecl>    superTypeDeclRef);

            /// Check whether `subType` is a sub-type of `superTypeDeclRef`,
            /// and return a witness to the sub-type relationship if it holds
            /// (return null otherwise).
            ///
        Val* tryGetSubtypeWitness(
            Type*            subType,
            DeclRef<AggTypeDecl>    superTypeDeclRef);

            /// Check whether `type` conforms to `interfaceDeclRef`,
            /// and return a witness to the conformance if it holds
            /// (return null otherwise).
            ///
            /// This function is equivalent to `tryGetSubtypeWitness()`.
            ///
        Val* tryGetInterfaceConformanceWitness(
            Type*            type,
            DeclRef<InterfaceDecl>  interfaceDeclRef);

        Expr* createCastToSuperTypeExpr(
            Type*    toType,
            Expr*    fromExpr,
            Val*     witness);

        /// Does there exist an implicit conversion from `fromType` to `toType`?
        bool canConvertImplicitly(
            Type* toType,
            Type* fromType);

        Type* TryJoinTypeWithInterface(
            Type*            type,
            DeclRef<InterfaceDecl>      interfaceDeclRef);

        // Try to compute the "join" between two types
        Type* TryJoinTypes(
            Type*  left,
            Type*  right);

        // Try to solve a system of generic constraints.
        // The `system` argument provides the constraints.
        // The `varSubst` argument provides the list of constraint
        // variables that were created for the system.
        //
        // Returns a new substitution representing the values that
        // we solved for along the way.
        SubstitutionSet TrySolveConstraintSystem(
            ConstraintSystem*		system,
            DeclRef<GenericDecl>          genericDeclRef);


        // State related to overload resolution for a call
        // to an overloaded symbol
        struct OverloadResolveContext
        {
            enum class Mode
            {
                // We are just checking if a candidate works or not
                JustTrying,

                // We want to actually update the AST for a chosen candidate
                ForReal,
            };

            // Location to use when reporting overload-resolution errors.
            SourceLoc loc;

            // The original expression (if any) that triggered things
            Expr* originalExpr = nullptr;

            // Source location of the "function" part of the expression, if any
            SourceLoc       funcLoc;

            // The original arguments to the call
            Index argCount = 0;
            Expr** args = nullptr;
            Type** argTypes = nullptr;

            Index getArgCount() { return argCount; }
            Expr*& getArg(Index index) { return args[index]; }
            Type*& getArgType(Index index)
            {
                if(argTypes)
                    return argTypes[index];
                else
                    return getArg(index)->type.type;
            }
            Type* getArgTypeForInference(Index index, SemanticsVisitor* semantics)
            {
                if(argTypes)
                    return argTypes[index];
                else
                    return semantics->maybeResolveOverloadedExpr(getArg(index), LookupMask::Default, nullptr)->type;
            }

            bool disallowNestedConversions = false;

            Expr* baseExpr = nullptr;

            // Are we still trying out candidates, or are we
            // checking the chosen one for real?
            Mode mode = Mode::JustTrying;

            // We store one candidate directly, so that we don't
            // need to do dynamic allocation on the list every time
            OverloadCandidate bestCandidateStorage;
            OverloadCandidate*	bestCandidate = nullptr;

            // Full list of all candidates being considered, in the ambiguous case
            List<OverloadCandidate> bestCandidates;
        };

        struct ParamCounts
        {
            UInt required;
            UInt allowed;
        };

        // count the number of parameters required/allowed for a callable
        ParamCounts CountParameters(FilteredMemberRefList<ParamDecl> params);

        // count the number of parameters required/allowed for a generic
        ParamCounts CountParameters(DeclRef<GenericDecl> genericRef);

        bool TryCheckOverloadCandidateArity(
            OverloadResolveContext&		context,
            OverloadCandidate const&	candidate);

        bool TryCheckOverloadCandidateFixity(
            OverloadResolveContext&		context,
            OverloadCandidate const&	candidate);

        bool TryCheckGenericOverloadCandidateTypes(
            OverloadResolveContext&	context,
            OverloadCandidate&		candidate);

        bool TryCheckOverloadCandidateTypes(
            OverloadResolveContext&	context,
            OverloadCandidate&		candidate);

        bool TryCheckOverloadCandidateDirections(
            OverloadResolveContext&		/*context*/,
            OverloadCandidate const&	/*candidate*/);

        // Create a witness that attests to the fact that `type`
        // is equal to itself.
        Val* createTypeEqualityWitness(
            Type*  type);

        // If `sub` is a subtype of `sup`, then return a value that
        // can serve as a "witness" for that fact.
        Val* tryGetSubtypeWitness(
            Type*    sub,
            Type*    sup);

        // In the case where we are explicitly applying a generic
        // to arguments (e.g., `G<A,B>`) check that the constraints
        // on those parameters are satisfied.
        //
        // Note: the constraints actually work as additional parameters/arguments
        // of the generic, and so we need to reify them into the final
        // argument list.
        //
        bool TryCheckOverloadCandidateConstraints(
            OverloadResolveContext&		context,
            OverloadCandidate const&	candidate);

        // Try to check an overload candidate, but bail out
        // if any step fails
        void TryCheckOverloadCandidate(
            OverloadResolveContext&		context,
            OverloadCandidate&			candidate);

        // Create the representation of a given generic applied to some arguments
        Expr* createGenericDeclRef(
            Expr*            baseExpr,
            Expr*            originalExpr,
            GenericSubstitution*   subst);

        // Take an overload candidate that previously got through
        // `TryCheckOverloadCandidate` above, and try to finish
        // up the work and turn it into a real expression.
        //
        // If the candidate isn't actually applicable, this is
        // where we'd start reporting the issue(s).
        Expr* CompleteOverloadCandidate(
            OverloadResolveContext&		context,
            OverloadCandidate&			candidate);

        // Implement a comparison operation between overload candidates,
        // so that the better candidate compares as less-than the other
        int CompareOverloadCandidates(
            OverloadCandidate*	left,
            OverloadCandidate*	right);

            /// If `declRef` representations a specialization of a generic, returns the number of specialized generic arguments.
            /// Otherwise, returns zero.
            ///
        Int getSpecializedParamCount(DeclRef<Decl> const& declRef);

            /// Compare items `left` and `right` produced by lookup, to see if one should be favored for overloading.
        int CompareLookupResultItems(
            LookupResultItem const& left,
            LookupResultItem const& right);

            /// Compare items `left` and `right` being considered as overload candidates, and determine if one should be favored for structural reasons.
        int compareOverloadCandidateSpecificity(
            LookupResultItem const& left,
            LookupResultItem const& right);

        void AddOverloadCandidateInner(
            OverloadResolveContext& context,
            OverloadCandidate&		candidate);

        void AddOverloadCandidate(
            OverloadResolveContext& context,
            OverloadCandidate&		candidate);

        void AddFuncOverloadCandidate(
            LookupResultItem			item,
            DeclRef<CallableDecl>             funcDeclRef,
            OverloadResolveContext&		context);

        void AddFuncOverloadCandidate(
            FuncType*		/*funcType*/,
            OverloadResolveContext&	/*context*/);

        // Add a candidate callee for overload resolution, based on
        // calling a particular `ConstructorDecl`.
        void AddCtorOverloadCandidate(
            LookupResultItem            typeItem,
            Type*                type,
            DeclRef<ConstructorDecl>    ctorDeclRef,
            OverloadResolveContext&     context,
            Type*                resultType);

        // If the given declaration has generic parameters, then
        // return the corresponding `GenericDecl` that holds the
        // parameters, etc.
        GenericDecl* GetOuterGeneric(Decl* decl);

        // Try to find a unification for two values
        bool TryUnifyVals(
            ConstraintSystem&	constraints,
            Val*			fst,
            Val*			snd);

        bool tryUnifySubstitutions(
            ConstraintSystem&       constraints,
            Substitutions*   fst,
            Substitutions*   snd);

        bool tryUnifyGenericSubstitutions(
            ConstraintSystem&           constraints,
            GenericSubstitution* fst,
            GenericSubstitution* snd);

        bool TryUnifyTypeParam(
            ConstraintSystem&				constraints,
            GenericTypeParamDecl*	typeParamDecl,
            Type*			type);

        bool TryUnifyIntParam(
            ConstraintSystem&               constraints,
            GenericValueParamDecl*	paramDecl,
            IntVal*                  val);

        bool TryUnifyIntParam(
            ConstraintSystem&       constraints,
            DeclRef<VarDeclBase> const&   varRef,
            IntVal*          val);

        bool TryUnifyTypesByStructuralMatch(
            ConstraintSystem&       constraints,
            Type*  fst,
            Type*  snd);

        bool TryUnifyTypes(
            ConstraintSystem&       constraints,
            Type*  fst,
            Type*  snd);

        bool TryUnifyConjunctionType(
            ConstraintSystem&   constraints,
            AndType*            fst,
            Type*               snd);

        // Is the candidate extension declaration actually applicable to the given type
        DeclRef<ExtensionDecl> ApplyExtensionToType(
            ExtensionDecl*  extDecl,
            Type*    type);

        // Take a generic declaration and try to specialize its parameters
        // so that the resulting inner declaration can be applicable in
        // a particular context...
        DeclRef<Decl> SpecializeGenericForOverload(
            DeclRef<GenericDecl>    genericDeclRef,
            OverloadResolveContext& context);

        void AddTypeOverloadCandidates(
            Type*	        type,
            OverloadResolveContext&	context);

        void AddDeclRefOverloadCandidates(
            LookupResultItem		item,
            OverloadResolveContext&	context);

        void AddOverloadCandidates(
            LookupResult const&     result,
            OverloadResolveContext&	context);

        void AddOverloadCandidates(
            Expr*	funcExpr,
            OverloadResolveContext&			context);

        String getCallSignatureString(
            OverloadResolveContext&     context);

        Expr* ResolveInvoke(InvokeExpr * expr);

        void AddGenericOverloadCandidate(
            LookupResultItem		baseItem,
            OverloadResolveContext&	context);

        void AddGenericOverloadCandidates(
            Expr*	baseExpr,
            OverloadResolveContext&			context);

            /// Check a generic application where the operands have already been checked.
        Expr* checkGenericAppWithCheckedArgs(GenericAppExpr* genericAppExpr);

        Expr* CheckExpr(Expr* expr);

        Expr* CheckInvokeExprWithCheckedOperands(InvokeExpr *expr);

        // Get the type to use when referencing a declaration
        QualType GetTypeForDeclRef(DeclRef<Decl> declRef, SourceLoc loc);

        //
        //
        //

        Expr* MaybeDereference(Expr* inExpr);

        Expr* CheckMatrixSwizzleExpr(
            MemberExpr* memberRefExpr,
            Type*      baseElementType,
            IntegerLiteralValue        baseElementRowCount,
            IntegerLiteralValue        baseElementColCount);

        Expr* CheckMatrixSwizzleExpr(
            MemberExpr* memberRefExpr,
            Type*      baseElementType,
            IntVal*        baseElementRowCount,
            IntVal*        baseElementColCount);

        Expr* CheckSwizzleExpr(
            MemberExpr* memberRefExpr,
            Type*      baseElementType,
            IntegerLiteralValue         baseElementCount);

        Expr* CheckSwizzleExpr(
            MemberExpr*	memberRefExpr,
            Type*		baseElementType,
            IntVal*				baseElementCount);

            /// Perform semantic checking of an assignment where the operands have already been checked.
        Expr* checkAssignWithCheckedOperands(AssignExpr* expr);

        // Look up a static member
        // @param expr Can be StaticMemberExpr or MemberExpr
        // @param baseExpression Is the underlying type expression determined from resolving expr
        Expr* _lookupStaticMember(DeclRefExpr* expr, Expr* baseExpression);

        Expr* visitStaticMemberExpr(StaticMemberExpr* expr);

            /// Perform checking operations required for the "base" expression of a member-reference like `base.someField`
        Expr* checkBaseForMemberExpr(Expr* baseExpr);

        Expr* lookupMemberResultFailure(
            DeclRefExpr*     expr,
            QualType const& baseType);

        SharedSemanticsContext& operator=(const SharedSemanticsContext &) = delete;


        //

        void importModuleIntoScope(Scope* scope, ModuleDecl* moduleDecl);
    };

    struct SemanticsExprVisitor
        : public SemanticsVisitor
        , ExprVisitor<SemanticsExprVisitor, Expr*>
    {
    public:
        SemanticsExprVisitor(SharedSemanticsContext* shared)
            : SemanticsVisitor(shared)
        {}

        Expr* visitBoolLiteralExpr(BoolLiteralExpr* expr);
        Expr* visitIntegerLiteralExpr(IntegerLiteralExpr* expr);
        Expr* visitFloatingPointLiteralExpr(FloatingPointLiteralExpr* expr);
        Expr* visitStringLiteralExpr(StringLiteralExpr* expr);

        Expr* visitIndexExpr(IndexExpr* subscriptExpr);

        Expr* visitParenExpr(ParenExpr* expr);

        Expr* visitAssignExpr(AssignExpr* expr);

        Expr* visitGenericAppExpr(GenericAppExpr* genericAppExpr);

        Expr* visitSharedTypeExpr(SharedTypeExpr* expr);

        Expr* visitTaggedUnionTypeExpr(TaggedUnionTypeExpr* expr);

        Expr* visitInvokeExpr(InvokeExpr *expr);

        Expr* visitVarExpr(VarExpr *expr);

        Expr* visitTypeCastExpr(TypeCastExpr * expr);

        //
        // Some syntax nodes should not occur in the concrete input syntax,
        // and will only appear *after* checking is complete. We need to
        // deal with this cases here, even if they are no-ops.
        //

    #define CASE(NAME)                                  \
        Expr* visit##NAME(NAME* expr)            \
        {                                               \
            SLANG_DIAGNOSE_UNEXPECTED(getSink(), expr,  \
                "should not appear in input syntax");   \
            return expr;                                \
        }

        CASE(DerefExpr)
        CASE(MatrixSwizzleExpr)
        CASE(SwizzleExpr)
        CASE(OverloadedExpr)
        CASE(OverloadedExpr2)
        CASE(AggTypeCtorExpr)
        CASE(CastToSuperTypeExpr)
        CASE(LetExpr)
        CASE(ExtractExistentialValueExpr)

    #undef CASE

        Expr* visitStaticMemberExpr(StaticMemberExpr* expr);

        Expr* visitMemberExpr(MemberExpr * expr);

        Expr* visitInitializerListExpr(InitializerListExpr* expr);

        Expr* visitThisExpr(ThisExpr* expr);
        Expr* visitThisTypeExpr(ThisTypeExpr* expr);
        Expr* visitAndTypeExpr(AndTypeExpr* expr);
    };

    struct SemanticsStmtVisitor
        : public SemanticsVisitor
        , StmtVisitor<SemanticsStmtVisitor>
    {
        SemanticsStmtVisitor(SharedSemanticsContext* shared, FunctionDeclBase* parentFunc, OuterStmtInfo* outerStmts)
            : SemanticsVisitor(shared)
            , m_parentFunc(parentFunc)
            , m_outerStmts(outerStmts)
        {}

            /// The parent function (if any) that surrounds the statement being checked.
        FunctionDeclBase* m_parentFunc = nullptr;

            /// The linked list of lexically surrounding statements.
        OuterStmtInfo* m_outerStmts = nullptr;

        FunctionDeclBase* getParentFunc() { return m_parentFunc; }

        void checkStmt(Stmt* stmt);

        template<typename T>
        T* FindOuterStmt();

        void visitDeclStmt(DeclStmt* stmt);

        void visitBlockStmt(BlockStmt* stmt);

        void visitSeqStmt(SeqStmt* stmt);

        void visitBreakStmt(BreakStmt *stmt);

        void visitContinueStmt(ContinueStmt *stmt);

        void visitDoWhileStmt(DoWhileStmt *stmt);

        void visitForStmt(ForStmt *stmt);

        void visitCompileTimeForStmt(CompileTimeForStmt* stmt);

        void visitSwitchStmt(SwitchStmt* stmt);

        void visitCaseStmt(CaseStmt* stmt);

        void visitDefaultStmt(DefaultStmt* stmt);

        void visitIfStmt(IfStmt *stmt);

        void visitUnparsedStmt(UnparsedStmt*);

        void visitEmptyStmt(EmptyStmt*);

        void visitDiscardStmt(DiscardStmt*);

        void visitReturnStmt(ReturnStmt *stmt);

        void visitWhileStmt(WhileStmt *stmt);
        
        void visitGpuForeachStmt(GpuForeachStmt *stmt);

        void visitExpressionStmt(ExpressionStmt *stmt);
    };

    struct SemanticsDeclVisitorBase
        : public SemanticsVisitor
    {
        SemanticsDeclVisitorBase(SharedSemanticsContext* shared)
            : SemanticsVisitor(shared)
        {}

        void checkBodyStmt(Stmt* stmt, FunctionDeclBase* parentDecl)
        {
            checkStmt(stmt, parentDecl, nullptr);
        }

        void checkModule(ModuleDecl* programNode);
    };
}