summaryrefslogtreecommitdiff
path: root/source/slang/slang-ir-check-recursive-type.cpp
blob: ee45417358dcef317da33d93e449c42998c244ff (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
#include "slang-ir-check-recursive-type.h"

#include "slang-ir-util.h"

namespace Slang
{
bool checkTypeRecursionImpl(
    HashSet<IRInst*>& checkedTypes,
    HashSet<IRInst*>& stack,
    IRInst* type,
    IRInst* field,
    DiagnosticSink* sink)
{
    auto visitElementType = [&](IRInst* elementType, IRInst* field) -> bool
    {
        if (!stack.add(elementType))
        {
            sink->diagnose(field ? field : type, Diagnostics::recursiveType, type);
            return false;
        }
        if (checkedTypes.add(elementType))
            checkTypeRecursionImpl(checkedTypes, stack, elementType, field, sink);
        stack.remove(elementType);
        return true;
    };
    if (auto arrayType = as<IRArrayTypeBase>(type))
    {
        return visitElementType(arrayType->getElementType(), field);
    }
    else if (auto structType = as<IRStructType>(type))
    {
        for (auto sfield : structType->getFields())
            if (!visitElementType(sfield->getFieldType(), sfield))
                return false;
    }
    return true;
}

void checkTypeRecursion(HashSet<IRInst*>& checkedTypes, IRInst* type, DiagnosticSink* sink)
{
    HashSet<IRInst*> stack;
    if (checkedTypes.add(type))
    {
        stack.add(type);
        checkTypeRecursionImpl(checkedTypes, stack, type, nullptr, sink);
    }
}

void checkForRecursiveTypes(IRModule* module, DiagnosticSink* sink)
{
    HashSet<IRInst*> checkedTypes;
    for (auto globalInst : module->getGlobalInsts())
    {
        switch (globalInst->getOp())
        {
        case kIROp_StructType:
            {
                checkTypeRecursion(checkedTypes, globalInst, sink);
            }
            break;
        }
    }
}

} // namespace Slang