aboutsummaryrefslogtreecommitdiffstats
path: root/sources/shiboken6/ApiExtractor/abstractmetatype.cpp
blob: d47b25ef2e8740b01174b3bea6743178153cc3cc (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
/****************************************************************************
**
** Copyright (C) 2020 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt for Python.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "abstractmetatype.h"
#include "abstractmetabuilder.h"
#include "abstractmetalang.h"
#include "messages.h"
#include "typedatabase.h"
#include "typesystem.h"
#include "parser/codemodel.h"

#include "qtcompat.h"

#ifndef QT_NO_DEBUG_STREAM
#  include <QtCore/QDebug>
#endif

#include <QtCore/QHash>
#include <QtCore/QSharedData>
#include <QtCore/QSharedPointer>
#include <QtCore/QStack>

using namespace Qt::StringLiterals;

using AbstractMetaTypeCPtr = QSharedPointer<const AbstractMetaType>;

const QSet<QString> &AbstractMetaType::cppFloatTypes()
{
    static const QSet<QString> result{u"double"_s, u"float"_s};
    return result;
}

const QSet<QString> &AbstractMetaType::cppSignedCharTypes()
{
    static const QSet<QString> result{u"char"_s, u"signed char"_s};
    return result;
}

const QSet<QString> &AbstractMetaType::cppUnsignedCharTypes()
{
    static const QSet<QString> result{u"unsigned char"_s};
    return result;
}

const QSet<QString> &AbstractMetaType::cppCharTypes()
{
    static const QSet<QString> result = cppSignedCharTypes() | cppUnsignedCharTypes();
    return result;
}

const QSet<QString> &AbstractMetaType::cppSignedIntTypes()
{
    static QSet<QString> result;
    if (result.isEmpty()) {
        result = {u"char"_s, u"signed char"_s, u"short"_s, u"short int"_s,
                  u"signed short"_s, u"signed short int"_s,
                  u"int"_s, u"signed int"_s,
                  u"long"_s, u"long int"_s,
                  u"signed long"_s, u"signed long int"_s,
                  u"long long"_s, u"long long int"_s,
                  u"signed long long int"_s,
                  u"ptrdiff_t"_s};
        result |= cppSignedCharTypes();
    }
    return result;
}

const QSet<QString> &AbstractMetaType::cppUnsignedIntTypes()
{
    static QSet<QString> result;
    if (result.isEmpty()) {
        result = {u"unsigned short"_s, u"unsigned short int"_s,
                  u"unsigned"_s, u"unsigned int"_s,
                  u"unsigned long"_s, u"unsigned long int"_s,
                  u"unsigned long long"_s,
                  u"unsigned long long int"_s,
                  u"size_t"_s};
        result |= cppUnsignedCharTypes();
    }
    return result;
}

const QSet<QString> &AbstractMetaType::cppIntegralTypes()
{
    static QSet<QString> result;
    if (result.isEmpty()) {
        result |= cppSignedIntTypes();
        result |= cppUnsignedIntTypes();
        result.insert(u"bool"_s);
    }
    return result;
}

const QSet<QString> &AbstractMetaType::cppPrimitiveTypes()
{
    static QSet<QString> result;
    if (result.isEmpty()) {
        result |= cppIntegralTypes();
        result |= cppFloatTypes();
        result.insert(u"wchar_t"_s);
    }
    return result;
}

class AbstractMetaTypeData : public QSharedData
{
public:
    AbstractMetaTypeData(const TypeEntry *t);

    int actualIndirections() const;
    bool passByConstRef() const;
    bool passByValue() const;
    AbstractMetaType::TypeUsagePattern determineUsagePattern() const;
    bool hasTemplateChildren() const;
    QString formatSignature(bool minimal) const;
    QString formatPythonSignature() const;
    bool isEquivalent(const AbstractMetaTypeData &rhs) const;
    bool equals(const AbstractMetaTypeData &rhs) const;

    template <class Predicate>
    bool generateOpaqueContainer(Predicate p) const;

    const TypeEntry *m_typeEntry;
    AbstractMetaTypeList m_instantiations;
    mutable QString m_cachedCppSignature;
    mutable QString m_cachedPythonSignature;
    QString m_originalTypeDescription;

    int m_arrayElementCount = -1;
    AbstractMetaTypeCPtr m_arrayElementType;
    AbstractMetaTypeCPtr m_originalTemplateType;
    AbstractMetaTypeCPtr m_viewOn;
    AbstractMetaType::Indirections m_indirections;

    AbstractMetaType::TypeUsagePattern m_pattern = AbstractMetaType::VoidPattern;
    uint m_constant : 1;
    uint m_volatile : 1;
    uint m_signaturesDirty : 1;
    uint m_reserved : 29; // unused

    ReferenceType m_referenceType = NoReference;
    AbstractMetaTypeList m_children;
};

AbstractMetaTypeData::AbstractMetaTypeData(const TypeEntry *t) :
    m_typeEntry(t),
    m_constant(false),
    m_volatile(false),
    m_signaturesDirty(true),
    m_reserved(0)
{
}

AbstractMetaType::AbstractMetaType(const TypeEntry *t) : d(new AbstractMetaTypeData(t))
{
    Q_ASSERT(t);
}

AbstractMetaType::AbstractMetaType()
{
    *this = AbstractMetaType::createVoid();
}

AbstractMetaType &AbstractMetaType::operator=(const AbstractMetaType &) = default;

AbstractMetaType::AbstractMetaType(const AbstractMetaType &rhs) = default;

AbstractMetaType::AbstractMetaType(AbstractMetaType &&) = default;

AbstractMetaType &AbstractMetaType::operator=(AbstractMetaType &&) = default;

AbstractMetaType::~AbstractMetaType() = default;

QString AbstractMetaType::package() const
{
    return d->m_typeEntry->targetLangPackage();
}

QString AbstractMetaType::name() const
{
    return d->m_typeEntry->targetLangEntryName();
}

QString AbstractMetaType::fullName() const
{
    return d->m_typeEntry->qualifiedTargetLangName();
}

void AbstractMetaType::setTypeUsagePattern(AbstractMetaType::TypeUsagePattern pattern)
{
    if (d->m_pattern != pattern)
        d->m_pattern = pattern;
}

AbstractMetaType::TypeUsagePattern AbstractMetaType::typeUsagePattern() const
{
    return d->m_pattern;
}

bool AbstractMetaType::hasInstantiations() const
{
    return !d->m_instantiations.isEmpty();
}

void AbstractMetaType::addInstantiation(const AbstractMetaType &inst)
{
    d->m_instantiations << inst;
}

void AbstractMetaType::setInstantiations(const AbstractMetaTypeList &insts)
{
    if (insts != d->m_instantiations)
        d->m_instantiations = insts;
}

const AbstractMetaTypeList &AbstractMetaType::instantiations() const
{
    return d->m_instantiations;
}

// For applying the <array> function argument modification: change into a type
// where "int *" becomes "int[]".
bool AbstractMetaType::applyArrayModification(QString *errorMessage)
{

    if (d->m_pattern == AbstractMetaType::NativePointerAsArrayPattern) {
        *errorMessage = u"<array> modification already applied."_s;
        return false;
    }
    if (!d->m_arrayElementType.isNull())  {
        QTextStream(errorMessage) << "The type \"" << cppSignature()
            << "\" is an array of " << d->m_arrayElementType->name() << '.';
        return false;
    }
    if (d->m_indirections.isEmpty()) {
        QTextStream(errorMessage) << "The type \"" << cppSignature()
            << "\" does not have indirections.";
        return false;
    }
    // Element type to be used for ArrayHandle<>, strip constness.

    auto elementType = new AbstractMetaType(*this);
    auto indir = indirectionsV();
    indir.pop_front();
    elementType->setIndirectionsV(indir);
    elementType->setConstant(false);
    elementType->setVolatile(false);
    elementType->decideUsagePattern();
    d->m_arrayElementType.reset(elementType);
    d->m_pattern = AbstractMetaType::NativePointerAsArrayPattern;
    return true;
}

const TypeEntry *AbstractMetaType::typeEntry() const
{
    return d->m_typeEntry;
}

void AbstractMetaType::setTypeEntry(const TypeEntry *type)
{
    if (d->m_typeEntry != type)
        d->m_typeEntry = type;
}

void AbstractMetaType::setOriginalTypeDescription(const QString &otd)
{
    if (d->m_originalTypeDescription != otd)
        d->m_originalTypeDescription = otd;
}

QString AbstractMetaType::originalTypeDescription() const
{
    return d->m_originalTypeDescription;
}

void AbstractMetaType::setOriginalTemplateType(const AbstractMetaType &type)
{
    if (d->m_originalTemplateType.isNull() || *d->m_originalTemplateType != type)
        d->m_originalTemplateType.reset(new AbstractMetaType(type));
}

const AbstractMetaType *AbstractMetaType::originalTemplateType() const
{
    return d->m_originalTemplateType.data();
}

AbstractMetaType AbstractMetaType::getSmartPointerInnerType() const
{
    Q_ASSERT(isSmartPointer());
    Q_ASSERT(!d->m_instantiations.isEmpty());
    AbstractMetaType innerType = d->m_instantiations.at(0);
    return innerType;
}

QString AbstractMetaType::getSmartPointerInnerTypeName() const
{
    Q_ASSERT(isSmartPointer());
    return getSmartPointerInnerType().name();
}

AbstractMetaTypeList AbstractMetaType::nestedArrayTypes() const
{
    AbstractMetaTypeList result;
    switch (d->m_pattern) {
    case ArrayPattern:
        for (AbstractMetaType t = *this; t.typeUsagePattern() == ArrayPattern; ) {
            const AbstractMetaType *elt = t.arrayElementType();
            result.append(*elt);
            t = *elt;
        }
        break;
    case NativePointerAsArrayPattern:
        result.append(*d->m_arrayElementType.data());
        break;
    default:
        break;
    }
    return result;
}

bool AbstractMetaTypeData::passByConstRef() const
{
    return m_constant && m_referenceType == LValueReference && m_indirections.isEmpty();
}

bool AbstractMetaType::passByConstRef() const
{
    return d->passByConstRef();
}

bool AbstractMetaTypeData::passByValue() const
{
    return m_referenceType == NoReference && m_indirections.isEmpty();
}

bool AbstractMetaType::passByValue() const
{
    return d->passByValue();
}

ReferenceType AbstractMetaType::referenceType() const
{
    return d->m_referenceType;
}

void AbstractMetaType::setReferenceType(ReferenceType ref)
{
    if (d->m_referenceType != ref) {
        d->m_referenceType = ref;
        d->m_signaturesDirty = true;
    }
}

int AbstractMetaTypeData::actualIndirections() const
{
    return m_indirections.size() + (m_referenceType == LValueReference ? 1 : 0);
}

int AbstractMetaType::actualIndirections() const
{
    return d->actualIndirections();
}

AbstractMetaType::Indirections AbstractMetaType::indirectionsV() const
{
    return d->m_indirections;
}

void AbstractMetaType::setIndirectionsV(const AbstractMetaType::Indirections &i)
{
    if (d->m_indirections != i) {
        d->m_indirections = i;
        d->m_signaturesDirty = true;
    }
}

void AbstractMetaType::clearIndirections()
{
    if (!d->m_indirections.isEmpty()) {
        d->m_indirections.clear();
        d->m_signaturesDirty = true;
    }
}

int AbstractMetaType::indirections() const
{
    return d->m_indirections.size();
}

void AbstractMetaType::setIndirections(int indirections)
{
    const Indirections newValue(indirections, Indirection::Pointer);
    if (d->m_indirections != newValue) {
        d->m_indirections = newValue;
        d->m_signaturesDirty = true;
    }
}

void AbstractMetaType::addIndirection(Indirection i)
{
    d->m_indirections.append(i);
}

void AbstractMetaType::setArrayElementCount(int n)
{
    if (d->m_arrayElementCount != n) {
        d->m_arrayElementCount = n;
        d->m_signaturesDirty = true;
    }
}

int AbstractMetaType::arrayElementCount() const
{
    return d->m_arrayElementCount;
}

const AbstractMetaType *AbstractMetaType::arrayElementType() const
{
    return d->m_arrayElementType.data();
}

void AbstractMetaType::setArrayElementType(const AbstractMetaType &t)
{
    if (d->m_arrayElementType.isNull() || *d->m_arrayElementType != t) {
        d->m_arrayElementType.reset(new AbstractMetaType(t));
        d->m_signaturesDirty = true;
    }
}

QString AbstractMetaType::cppSignature() const
{
    const AbstractMetaTypeData *cd = d.constData();
    if (cd->m_cachedCppSignature.isEmpty() || cd->m_signaturesDirty)
        cd->m_cachedCppSignature = formatSignature(false);
    return cd->m_cachedCppSignature;
}

QString AbstractMetaType::pythonSignature() const
{
    // PYSIDE-921: Handle container returntypes correctly.
    // This is now a clean reimplementation.
    const AbstractMetaTypeData *cd = d.constData();
    if (cd->m_cachedPythonSignature.isEmpty() || cd->m_signaturesDirty)
        cd->m_cachedPythonSignature = formatPythonSignature();
    return cd->m_cachedPythonSignature;
}

AbstractMetaType::TypeUsagePattern AbstractMetaTypeData::determineUsagePattern() const
{
    if (m_typeEntry->isTemplateArgument())
        return AbstractMetaType::TemplateArgument;

    if (m_typeEntry->type() == TypeEntry::ConstantValueType)
        return AbstractMetaType::NonTypeTemplateArgument;

    if (m_typeEntry->isPrimitive() && (actualIndirections() == 0 || passByConstRef()))
        return AbstractMetaType::PrimitivePattern;

    if (m_typeEntry->isVoid()) {
        return m_arrayElementCount < 0 && m_referenceType == NoReference
            && m_indirections.isEmpty() && m_constant == 0 && m_volatile == 0
            ? AbstractMetaType::VoidPattern : AbstractMetaType::NativePointerPattern;
    }

    if (m_typeEntry->isVarargs())
        return AbstractMetaType::VarargsPattern;

    if (m_typeEntry->isEnum() && (actualIndirections() == 0 || passByConstRef()))
        return AbstractMetaType::EnumPattern;

    if (m_typeEntry->isObject()) {
        if (m_indirections.isEmpty() && m_referenceType == NoReference)
            return AbstractMetaType::ValuePattern;
        return AbstractMetaType::ObjectPattern;
    }

    if (m_typeEntry->isContainer() && m_indirections.isEmpty())
        return AbstractMetaType::ContainerPattern;

    if (m_typeEntry->isSmartPointer() && m_indirections.isEmpty())
        return AbstractMetaType::SmartPointerPattern;

    if (m_typeEntry->isFlags() && (actualIndirections() == 0 || passByConstRef()))
        return AbstractMetaType::FlagsPattern;

    if (m_typeEntry->isArray())
        return AbstractMetaType::ArrayPattern;

    if (m_typeEntry->isValue())
        return m_indirections.size() == 1 ? AbstractMetaType::ValuePointerPattern : AbstractMetaType::ValuePattern;

    return AbstractMetaType::NativePointerPattern;
}

AbstractMetaType::TypeUsagePattern AbstractMetaType::determineUsagePattern() const
{
    return d->determineUsagePattern();
}

void AbstractMetaType::decideUsagePattern()
{
    TypeUsagePattern pattern = determineUsagePattern();
    if (d->m_typeEntry->isObject() && indirections() == 1
        && d->m_referenceType == LValueReference && isConstant()) {
        // const-references to pointers can be passed as pointers
        setReferenceType(NoReference);
        setConstant(false);
        pattern = ObjectPattern;
    }
    setTypeUsagePattern(pattern);
}

bool AbstractMetaTypeData::hasTemplateChildren() const
{
    QStack<AbstractMetaType> children;
    children << m_instantiations;

    // Recursively iterate over the children / descendants of the type, to check if any of them
    // corresponds to a template argument type.
    while (!children.isEmpty()) {
        AbstractMetaType child = children.pop();
        if (child.typeEntry()->isTemplateArgument())
            return true;
        children << child.instantiations();
    }
    return false;
}

bool AbstractMetaType::hasTemplateChildren() const
{
    return d->hasTemplateChildren();
}

static inline QString formatArraySize(int e)
{
    QString result;
    result += u'[';
    if (e >= 0)
        result += QString::number(e);
    result += u']';
    return result;
}

QString AbstractMetaTypeData::formatSignature(bool minimal) const
{
    QString result;
    if (m_constant)
        result += u"const "_s;
    if (m_volatile)
        result += u"volatile "_s;
    if (m_pattern == AbstractMetaType::ArrayPattern) {
        // Build nested array dimensions a[2][3] in correct order
        result += m_arrayElementType->minimalSignature();
        const int arrayPos = result.indexOf(u'[');
        if (arrayPos != -1)
            result.insert(arrayPos, formatArraySize(m_arrayElementCount));
        else
            result.append(formatArraySize(m_arrayElementCount));
    } else {
        result += m_typeEntry->qualifiedCppName();
    }
    if (!m_instantiations.isEmpty()) {
        result += u'<';
        if (minimal)
            result += u' ';
        for (int i = 0, size = m_instantiations.size(); i < size; ++i) {
            if (i > 0)
                result += u',';
            result += m_instantiations.at(i).minimalSignature();
        }
        result += u" >"_s;
    }

    if (!minimal && (!m_indirections.isEmpty() || m_referenceType != NoReference))
        result += u' ';
    for (Indirection i : m_indirections)
        result += TypeInfo::indirectionKeyword(i);
    switch (m_referenceType) {
    case NoReference:
        break;
    case LValueReference:
        result += u'&';
        break;
    case RValueReference:
        result += u"&&"_s;
        break;
    }
    return result;
}

QString AbstractMetaType::formatSignature(bool minimal) const
{
    return d->formatSignature(minimal);
}

QString AbstractMetaTypeData::formatPythonSignature() const
{
    /*
     * This is a version of the above, more suitable for Python.
     * We avoid extra keywords that are not needed in Python.
     * We prepend the package name, unless it is a primitive type.
     *
     * Primitive types like 'int', 'char' etc.:
     * When we have a primitive with an indirection, we use that '*'
     * character for later postprocessing, since those indirections
     * need to be modified into a result tuple.
     * Smart pointer instantiations: Drop the package
     */
    QString result;
    if (m_pattern == AbstractMetaType::NativePointerAsArrayPattern)
        result += u"array "_s;
    // We no longer use the "const" qualifier for heuristics. Instead,
    // NativePointerAsArrayPattern indicates when we have <array> in XML.
    // if (m_typeEntry->isPrimitive() && isConstant())
    //     result += QLatin1String("const ");
    if (!m_typeEntry->isPrimitive() && !m_typeEntry->isSmartPointer()) {
        const QString package = m_typeEntry->targetLangPackage();
        if (!package.isEmpty())
            result += package + u'.';
    }
    if (m_pattern == AbstractMetaType::ArrayPattern) {
        // Build nested array dimensions a[2][3] in correct order
        result += m_arrayElementType->formatPythonSignature();
        const int arrayPos = result.indexOf(u'[');
        if (arrayPos != -1)
            result.insert(arrayPos, formatArraySize(m_arrayElementCount));
        else
            result.append(formatArraySize(m_arrayElementCount));
    } else {
        result += m_typeEntry->targetLangName();
    }
    if (!m_instantiations.isEmpty()) {
        result += u'[';
        for (int i = 0, size = m_instantiations.size(); i < size; ++i) {
            if (i > 0)
                result += u", "_s;
            result += m_instantiations.at(i).formatPythonSignature();
        }
        result += u']';
    }
    if (m_typeEntry->isPrimitive())
        for (Indirection i : m_indirections)
            result += TypeInfo::indirectionKeyword(i);
    // If it is a flags type, we replace it with the full name:
    // "PySide6.QtCore.Qt.ItemFlags" instead of "PySide6.QtCore.QFlags<Qt.ItemFlag>"
    if (m_typeEntry->isFlags()) {
        // PYSIDE-1735: We need to provide both the flags type and the original enum type
        //              as a choice at runtime.
        auto flagsTypeEntry = static_cast<const FlagsTypeEntry *>(m_typeEntry);
        auto enumTypeEntry = flagsTypeEntry->originator();
        result = m_typeEntry->targetLangPackage() + u".^^"_s
               + flagsTypeEntry->targetLangName() + u"^^"_s
               + enumTypeEntry->targetLangName() + u"^^"_s;
    }

    result.replace(u"::"_s, u"."_s);
    return result;
}

QString AbstractMetaType::formatPythonSignature() const
{
    return d->formatPythonSignature();
}

bool AbstractMetaType::isCppPrimitive() const
{
    return d->m_pattern == PrimitivePattern && d->m_typeEntry->isCppPrimitive();
}

bool AbstractMetaType::isConstant() const
{
    return d->m_constant;
}

void AbstractMetaType::setConstant(bool constant)
{
    if (d->m_constant != constant) {
        d->m_constant = constant;
        d->m_signaturesDirty = true;
    }
}

bool AbstractMetaType::isVolatile() const
{
    return d->m_volatile;
}

void AbstractMetaType::setVolatile(bool v)
{
    if (d->m_volatile != v) {
        d->m_volatile = v;
        d->m_signaturesDirty = true;\
    }
}

static bool equalsCPtr(const AbstractMetaTypeCPtr &t1, const AbstractMetaTypeCPtr &t2)
{
    if (t1.isNull() != t2.isNull())
        return false;
    return t1.isNull() || *t1 == *t2;
}

bool AbstractMetaTypeData::isEquivalent(const AbstractMetaTypeData &rhs) const
{
    if (m_typeEntry != rhs.m_typeEntry
        || m_indirections != rhs.m_indirections
        || m_arrayElementCount != rhs.m_arrayElementCount) {
        return false;
    }

    if (!equalsCPtr(m_arrayElementType, rhs.m_arrayElementType))
        return false;

    if (!equalsCPtr(m_viewOn, rhs.m_viewOn))
        return false;

    if (m_instantiations != rhs.m_instantiations)
        return false;
    return true;
}

bool AbstractMetaTypeData::equals(const AbstractMetaTypeData &rhs) const
{
    return m_constant == rhs.m_constant && m_volatile == rhs.m_volatile
        && m_referenceType == rhs.m_referenceType && isEquivalent(rhs);
}

bool AbstractMetaType::equals(const AbstractMetaType &rhs) const
{
    return d->equals(*rhs.d);
}

bool AbstractMetaType::isEquivalent(const AbstractMetaType &rhs) const
{
    return  d->isEquivalent(*rhs.d);
}

const AbstractMetaType *AbstractMetaType::viewOn() const
{
    return d->m_viewOn.data();
}

void AbstractMetaType::setViewOn(const AbstractMetaType &v)
{
    if (d->m_viewOn.isNull() || *d->m_viewOn != v)
        d->m_viewOn.reset(new AbstractMetaType(v));
}

AbstractMetaType AbstractMetaType::createVoid()
{
    static QScopedPointer<AbstractMetaType> metaType;
    if (metaType.isNull()) {
        static const TypeEntry *voidTypeEntry = TypeDatabase::instance()->findType(u"void"_s);
        Q_ASSERT(voidTypeEntry);
        metaType.reset(new AbstractMetaType(voidTypeEntry));
        metaType->decideUsagePattern();
    }
    return *metaType.data();
}

void AbstractMetaType::dereference(QString *type)
{
    type->prepend(u"(*"_s);
    type->append(u')');
}

void AbstractMetaType::applyDereference(QString *type, qsizetype n)
{
    if (n == 0)
        return;

    const char c = n > 0 ? '*' : '&';
    type->prepend(QString(qAbs(n), QLatin1Char(c)));
    type->prepend(u'(');
    type->append(u')');
}

bool AbstractMetaType::stripDereference(QString *type)
{
    if (type->startsWith(u"(*") && type->endsWith(u')')) {
        type->chop(1);
        type->remove(0, 2);
        *type = type->trimmed();
        return true;
    }
    if (type->startsWith(u'*')) {
        type->remove(0, 1);
        *type = type->trimmed();
        return true;
    }
    return false;
}

// Query functions for generators
bool AbstractMetaType::isObjectType() const
{
    return d->m_typeEntry->isObject();
}

bool AbstractMetaType::isPointer() const
{
    return !d->m_indirections.isEmpty()
        || isNativePointer() || isValuePointer();
}

bool AbstractMetaType::isPointerToConst() const
{
    return d->m_constant && !d->m_indirections.isEmpty()
        && d->m_indirections.constLast() != Indirection::ConstPointer;
}

bool AbstractMetaType::isCString() const
{
    return isNativePointer()
        && d->m_indirections.size() == 1
        && name() == u"char";
}

bool AbstractMetaType::isVoidPointer() const
{
    return isNativePointer()
        && d->m_indirections.size() == 1
        && name() == u"void";
}

bool AbstractMetaType::isUserPrimitive() const
{
    return d->m_indirections.isEmpty() && d->m_typeEntry->isUserPrimitive();
}

bool AbstractMetaType::isObjectTypeUsedAsValueType() const
{
    return d->m_typeEntry->isObject() && d->m_referenceType == NoReference
        && d->m_indirections.isEmpty();
}

bool AbstractMetaType::isWrapperType() const
{
    return d->m_typeEntry->isWrapperType();
}

bool AbstractMetaType::isPointerToWrapperType() const
{
    return (isObjectType() && d->m_indirections.size() == 1) || isValuePointer();
}

bool AbstractMetaType::isWrapperPassedByReference() const
{
    return d->m_referenceType == LValueReference && isWrapperType()
           && !isPointer();
}

qsizetype AbstractMetaType::shouldDereferenceArgument() const
{
    if (isWrapperPassedByReference() || valueTypeWithCopyConstructorOnlyPassed()
        || isObjectTypeUsedAsValueType()) {
        return 1;
    }

    if (!d->m_typeEntry->isContainer())
        return 0;

    qsizetype result = -d->m_indirections.size();

    // For opaque containers, the cppArg in the generated code is a pointer
    if (generateOpaqueContainer())
        ++result;

    return result;
}

bool AbstractMetaType::isCppIntegralPrimitive() const
{
    return  d->m_typeEntry->isCppIntegralPrimitive();
}

bool AbstractMetaType::isExtendedCppPrimitive() const
{
    if (isCString() || isVoidPointer())
        return true;
    if (!d->m_indirections.isEmpty())
        return false;
    return d->m_typeEntry->isExtendedCppPrimitive();
}

bool AbstractMetaType::isValueTypeWithCopyConstructorOnly() const
{
    bool result = false;
    if (d->m_typeEntry->isComplex()) {
        const auto *cte = static_cast<const ComplexTypeEntry *>(d->m_typeEntry);
        result = cte->isValueTypeWithCopyConstructorOnly();
    }
    return result;
}

bool AbstractMetaType::valueTypeWithCopyConstructorOnlyPassed() const
{
    return (passByValue() || passByConstRef())
           && isValueTypeWithCopyConstructorOnly();
}

using AbstractMetaTypeCache = QHash<QString, AbstractMetaType>;

Q_GLOBAL_STATIC(AbstractMetaTypeCache, metaTypeFromStringCache)

std::optional<AbstractMetaType>
AbstractMetaType::fromString(QString typeSignature, QString *errorMessage)
{
    typeSignature = typeSignature.trimmed();
    if (typeSignature.startsWith(u"::"))
        typeSignature.remove(0, 2);

    auto &cache = *metaTypeFromStringCache();
    auto it = cache.find(typeSignature);
    if (it == cache.end()) {
        auto metaType =
            AbstractMetaBuilder::translateType(typeSignature, nullptr, {}, errorMessage);
        if (Q_UNLIKELY(!metaType.has_value())) {
            if (errorMessage)
                errorMessage->prepend(msgCannotBuildMetaType(typeSignature));
            return {};
        }
        it = cache.insert(typeSignature, metaType.value());
    }
    return it.value();
}

AbstractMetaType AbstractMetaType::fromTypeEntry(const TypeEntry *typeEntry)
{
    QString typeName = typeEntry->qualifiedCppName();
    if (typeName.startsWith(u"::"))
        typeName.remove(0, 2);
    auto &cache  = *metaTypeFromStringCache();
    auto it = cache.find(typeName);
    if (it != cache.end())
        return it.value();
    AbstractMetaType metaType(typeEntry);
    metaType.clearIndirections();
    metaType.setReferenceType(NoReference);
    metaType.setConstant(false);
    metaType.decideUsagePattern();
    cache.insert(typeName, metaType);
    return metaType;
}

AbstractMetaType AbstractMetaType::fromAbstractMetaClass(const AbstractMetaClass *metaClass)
{
    return fromTypeEntry(metaClass->typeEntry());
}

template <class Predicate> // Predicate(containerTypeEntry, signature)
bool AbstractMetaTypeData::generateOpaqueContainer(Predicate pred) const
{
    // Allow for passing containers by pointer as well.
    if (!m_typeEntry->isContainer())
        return false;
    if (m_indirections.size() > 1)
        return false;
    auto *containerTypeEntry = static_cast<const ContainerTypeEntry *>(m_typeEntry);
    auto kind = containerTypeEntry->containerKind();
    if (kind != ContainerTypeEntry::ListContainer)
        return false;
    const auto &instantation =  m_instantiations.constFirst();
    if (instantation.referenceType() != NoReference)
        return false;
    const QString signature = instantation.cppSignature();

    bool result = false;
    auto *instTypEntry = instantation.typeEntry();
    switch (instTypEntry->type()) {
    case TypeEntry::PrimitiveType:
    case TypeEntry::FlagsType:
    case TypeEntry::EnumType:
    case TypeEntry::BasicValueType:
    case TypeEntry::ObjectType:
    case TypeEntry::CustomType:
        result = pred(containerTypeEntry, signature);
        break;
    default:
        break;
    }
    return result;
}

// Simple predicate for checking whether an opaque container should be generated
static bool opaqueContainerPredicate(const ContainerTypeEntry *t,
                                     const QString &signature)
{
    return t->generateOpaqueContainer(signature);
}

bool AbstractMetaType::generateOpaqueContainer() const
{
    return d->generateOpaqueContainer(opaqueContainerPredicate);
}

// Helper for determining whether a function should return an opaque container,
// that is, the function return type is modified accordingly
// (cf AbstractMetaFunction::generateOpaqueContainerReturn())
bool AbstractMetaType::generateOpaqueContainerForGetter(const QString &modifiedType) const
{
    auto predicate = [&modifiedType](const ContainerTypeEntry *t, const QString &signature) {
        return t->opaqueContainerName(signature) == modifiedType;
    };
    return d->generateOpaqueContainer(predicate);
}

#ifndef QT_NO_DEBUG_STREAM
void AbstractMetaType::formatDebug(QDebug &debug) const
{
    debug << '"' << name() << '"';
    if (debug.verbosity() > 2 && !isVoid()) {
        auto te = typeEntry();
        debug << ", typeEntry=";
        if (debug.verbosity() > 3)
            debug << te;
        else
            debug << "(\"" << te->qualifiedCppName() << "\", " << te->type() << ')';
        debug << ", signature=\"" << cppSignature() << "\", pattern="
            << typeUsagePattern();
        const auto indirections = indirectionsV();
        if (!indirections.isEmpty()) {
            debug << ", indirections=";
            for (auto i : indirections)
                debug << ' ' << TypeInfo::indirectionKeyword(i);
        }
        if (referenceType())
            debug << ", reftype=" << referenceType();
        if (isConstant())
            debug << ", [const]";
        if (isVolatile())
            debug << ", [volatile]";
        if (isArray()) {
            debug << ", array of \"" << arrayElementType()->cppSignature()
                << "\", arrayElementCount="  << arrayElementCount();
        }
        const auto &instantiations = this->instantiations();
        if (const int instantiationsSize = instantiations.size()) {
            debug << ", instantiations[" << instantiationsSize << "]=<";
            for (int i = 0; i < instantiationsSize; ++i) {
                if (i)
                    debug << ", ";
                instantiations.at(i).formatDebug(debug);
            }
        }
        debug << '>';
        if (viewOn())
            debug << ", views " << viewOn()->name();
    }
}

QDebug operator<<(QDebug d, const AbstractMetaType &at)
{
    QDebugStateSaver saver(d);
    d.noquote();
    d.nospace();
    d << "AbstractMetaType(";
    at.formatDebug(d);
    d << ')';
    return d;
}

QDebug operator<<(QDebug d, const AbstractMetaType *at)
{
    QDebugStateSaver saver(d);
    d.noquote();
    d.nospace();
    if (at)
        d << *at;
    else
        d << "AbstractMetaType(0)";
    return d;
}

#endif // !QT_NO_DEBUG_STREAM