File: unsuretype.cpp

package info (click to toggle)
kdevelop-python 24.12.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 12,640 kB
  • sloc: python: 183,048; cpp: 18,798; xml: 140; sh: 14; makefile: 9
file content (247 lines) | stat: -rw-r--r-- 8,302 bytes parent folder | download
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
/*
    SPDX-FileCopyrightText: 2011 Sven Brauch <svenbrauch@googlemail.com>

    SPDX-License-Identifier: GPL-2.0-or-later
*/

#include "unsuretype.h"
#include "helpers.h"
#include "indexedcontainer.h"

#include <duchaindebug.h>

#include <language/duchain/types/typeregister.h>
#include <language/duchain/types/typesystem.h>
#include <language/duchain/types/typealiastype.h>
#include <language/duchain/types/containertypes.h>
#include <language/duchain/types/unsuretype.h>
#include <language/duchain/parsingenvironment.h>
#include <language/duchain/duchainlock.h>

#include <KLocalizedString>

namespace Python {

REGISTER_TYPE(UnsureType);

UnsureType::UnsureType() : KDevelop::UnsureType(createData<UnsureType>())
{
}

UnsureType::UnsureType(const UnsureType& rhs)
    : KDevelop::UnsureType(copyData<UnsureType>(*rhs.d_func()))
{

}

UnsureType::UnsureType(KDevelop::UnsureTypeData& data)
    : KDevelop::UnsureType(data)
{

}

const QList<AbstractType::Ptr> UnsureType::typesRecursive() const
{
    QList<AbstractType::Ptr> results;
    FOREACH_FUNCTION ( const IndexedType& type, d_func()->m_types ) {
        AbstractType::Ptr current = type.abstractType();
        AbstractType::Ptr resolved = Helper::resolveAliasType(current);
        if ( resolved->whichType() == AbstractType::TypeUnsure ) {
            results.append(resolved.staticCast<UnsureType>()->typesRecursive());
        }
        else
            results.append(current);
    }
    return results;
}

QString UnsureType::toString() const
{
    QString typeList;
    QVector<AbstractType::Ptr> types;
    auto is_new_type = [&types](const IndexedType newType) {
        for ( const auto& type : types ) {
            if ( type->indexed() == newType ) {
                return false;
            }
        }
        return true;
    };

    for ( AbstractType::Ptr type : typesRecursive() ) {
        if ( ! type ) {
            qCWarning(KDEV_PYTHON_DUCHAIN) << "Invalid type: " << type.data();
            continue;
        }

        const auto new_type = Helper::resolveAliasType(type);
        if ( is_new_type(new_type->indexed()) ) {
            types.append(new_type);
        }
    }

    auto count_and_remove = [&types](std::function<bool(AbstractType::Ptr)> match) -> bool {
        auto count = std::count_if(types.begin(), types.end(), match);
        if ( count < 3 ) {
            // nothing worth collapsing
            return false;
        }
        auto end = std::remove_if(types.begin(), types.end(), match);
        types.erase(end, types.end());
        return true;
    };

    QStringList collapsedTypes;
    if ( types.size() > 2 ) {
        // try to collapse the list, if possible
        using T = const AbstractType::Ptr&;
        auto have_callable = count_and_remove([](T t) { return t->whichType() == AbstractType::TypeFunction; });
        if ( have_callable ) {
            // TODO collapse arguments / return type
            collapsedTypes.append(i18nc("some object that can be called, in programming", "<callable>"));
        }
        auto have_iterable = count_and_remove([](T t) { return t.dynamicCast<IndexedContainer>() || t.dynamicCast<ListType>(); });
        if ( have_iterable ) {
            // TODO collapse element count / types
            collapsedTypes.append(i18nc("a set with some elements", "<iterable>"));
        }
    }

    int count = 0;
    for ( const auto& type : types ) {
        if ( count )
            typeList += QStringLiteral(", ");
        count += 1;

        typeList += type->toString();
    }
    for ( const auto& collapsed : collapsedTypes ) {
        if ( count )
            typeList += QStringLiteral(", ");
        count += 1;

        typeList += collapsed;
    }

    if ( count == 0 || count > 7 )
        return i18nc("refers to a type (in program code) which is not known", "mixed");
    if ( count == 1 )
        return typeList;
    return i18nc("refers to a type (in program code) which can have multiple values", "unsure (%1)", typeList);
}

KDevelop::AbstractType* UnsureType::clone() const
{
    UnsureType* n = new UnsureType(*this);
    return n;
}

AbstractType::WhichType UnsureType::whichType() const
{
    return AbstractType::TypeUnsure;
}

void UnsureType::addType(const IndexedType& indexed) {
    auto type = indexed.abstractType();
    auto hinted = type.dynamicCast<HintedType>(); // XXX: do we need a read locker here?
    if ( ! hinted ) {
        // if we aren't adding a HintedType the default implementation works
        KDevelop::UnsureType::addType(indexed);
        return;
    }
    auto& list = d_func_dynamic()->m_typesList();
    DUChainReadLocker lock;
    if (!hinted->isValid()) { // needs a read lock (as does most of the rest of the function)
        // can happen if the user saves the currently open document again before parsing has finished
        return;
    }
    // If there is already a HintedType in the list referring to the underlying type
    // we only add it if the context it was created in is the same.
    // Additionally, we also remove all HintedType instances that are no longer valid
    // to make sure the list doesn't grow infinitely large
    const auto newHintedTarget = hinted->type()->indexed();
    bool alreadyExists = false;
    for ( int j = 0; j < list.size(); j++ ) {
        const IndexedType oldIndexed = list.at(j);
        if (oldIndexed == indexed) {
            alreadyExists = true;
        }
        const auto& old = oldIndexed.abstractType();
        if ( auto oldHinted = old.dynamicCast<HintedType>() ) {
            if ( !alreadyExists ) {
                // only do these checks if we haven't already determined that it is a duplicate
                auto oldHintedTarget = oldHinted->type()->indexed();
                if ( oldHintedTarget == newHintedTarget ) {
                    if ( hinted->createdBy() == oldHinted->createdBy()) {
                        alreadyExists = true;
                    }
                }
            }
            if ( ! oldHinted->isValid() ) {
                // std::remove_if + erase() would be faster than remove() but this list won't have many entries
                // and the memcpy() cost is probably massively offset by the IndexedType -> AbstractType
                // lookup that we would have to duplicated if we had a separate check for duplicates loop
                list.remove(j);
                j--;
                continue;
            }
        }
    }
    if ( !alreadyExists ) {
        list.append(indexed);
    }
// #define CHECK_DUPLICATES
#ifdef CHECK_DUPLICATES
    if (list.size() > 1) {
        QString types;
        bool foundDuplicates = false;
        QStringList checkDuplicates;
        FOREACH_FUNCTION(const IndexedType& type2, d_func()->m_types) {
            auto t = type2.abstractType();
            auto str = t->toString();
            types += "\n    " + QString::number(type2.index());
            auto hinted = t.dynamicCast<HintedType>();
            while (hinted) {
                auto target = hinted->type();
                types += " (aka " + QString::number(target->indexed().index()) + ": " + target->toString()
                        +  " and context " + QString::number(hinted->createdBy().index()) + ")";
                hinted = target.dynamicCast<HintedType>();
            }
            types += " - " + t->toString() + " of type "  + typeid(*t).name();
            if (!foundDuplicates) {
                if (checkDuplicates.contains(str)) {
                    foundDuplicates = true;
                } else {
                    checkDuplicates.append(str);
                }
            }
        }
        if (foundDuplicates) {
            qWarning().nospace().noquote() << "found potential duplicates when adding " << typeid(*type).name()
                << " " << type->toString()
                << "(index = " << indexed.index() << ") ->" << types;
        }
    }
#endif
}

bool UnsureType::equals(const AbstractType* rhs) const
{
    if ( this == rhs ) {
        return true;
    }
    if ( ! dynamic_cast<const UnsureType*>(rhs) ) {
        return false;
    }
    if ( ! KDevelop::UnsureType::equals(rhs) ) {
        return false;
    }
    return true;
}

uint UnsureType::hash() const
{
    return KDevelop::UnsureType::hash() + 1;
}

}