aboutsummaryrefslogtreecommitdiffstats
path: root/tools/shadergen/parser.cpp
blob: c418eff279cc459e0a7e72d429d05ec717640adc (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
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
// Copyright (C) 2020 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "parser.h"

#include <QtCore/qdir.h>
#include <QtCore/qfileinfo.h>
#include <QtCore/qstringview.h>

#include <QtQml/qqmllist.h>

// Parsing
#include <QtQml/private/qqmljsengine_p.h>
#include <QtQml/private/qqmljslexer_p.h>
#include <QtQml/private/qqmljsparser_p.h>

#include <QtQuick3D/private/qquick3dobject_p.h>
#include <QtQuick3D/private/qquick3dviewport_p.h>
// Scene
#include <QtQuick3D/private/qquick3dsceneenvironment_p.h>
// Material(s)
#include <QtQuick3D/private/qquick3dprincipledmaterial_p.h>
#include <QtQuick3D/private/qquick3ddefaultmaterial_p.h>
#include <QtQuick3D/private/qquick3dcustommaterial_p.h>
// Lights
#include <QtQuick3D/private/qquick3dspotlight_p.h>
#include <QtQuick3D/private/qquick3dpointlight_p.h>
#include <QtQuick3D/private/qquick3ddirectionallight_p.h>

// Instancing
#include <QtQuick3D/private/qquick3dinstancing_p.h>

#include <QtQuick3D/private/qquick3dshaderutils_p.h>

#include <QtQuick3DUtils/private/qssginvasivelinkedlist_p.h>

#include <QtGui/qquaternion.h>

QT_BEGIN_NAMESPACE

template<typename T, T *T::*N = &T::next>
struct InvasiveListView : protected QSSGInvasiveSingleLinkedList<T, N>
{
    using QSSGInvasiveSingleLinkedList<T, N>::begin;
    using QSSGInvasiveSingleLinkedList<T, N>::end;
    using QSSGInvasiveSingleLinkedList<T, N>::m_head;

    explicit InvasiveListView(const T &obj) { m_head = &const_cast<T &>(obj); }
};

template <typename T> struct TypeInfo
{
    static constexpr const char *qmlTypeName() { return "Unknown"; }
    static constexpr int typeId() { return QMetaType::UnknownType; }
};

#define DECLARE_QQ3D_TYPE(CLASS, TYPE_NAME) \
template<> struct TypeInfo<CLASS> \
{ \
    static constexpr const char *qmlTypeName() { return #TYPE_NAME; } \
    inline static constexpr int typeId() { return qMetaTypeId<CLASS>(); } \
    inline static constexpr int qmlListTypeId() { return qMetaTypeId<QQmlListProperty<CLASS>>(); } \
}

DECLARE_QQ3D_TYPE(QQuick3DViewport, View3D);
DECLARE_QQ3D_TYPE(QQuick3DSceneEnvironment, SceneEnvironment);
DECLARE_QQ3D_TYPE(QQuick3DMaterial, Material);
DECLARE_QQ3D_TYPE(QQuick3DPrincipledMaterial, PrincipledMaterial);
DECLARE_QQ3D_TYPE(QQuick3DDefaultMaterial, DefaultMaterial);
DECLARE_QQ3D_TYPE(QQuick3DCustomMaterial, CustomMaterial);
DECLARE_QQ3D_TYPE(QQuick3DDirectionalLight, DirectionalLight);
DECLARE_QQ3D_TYPE(QQuick3DPointLight, PointLight);
DECLARE_QQ3D_TYPE(QQuick3DSpotLight, SpotLight);
DECLARE_QQ3D_TYPE(QQuick3DTexture, Texture);
DECLARE_QQ3D_TYPE(QQuick3DShaderUtilsTextureInput, TextureInput);
DECLARE_QQ3D_TYPE(QQuick3DModel, Model);
DECLARE_QQ3D_TYPE(QQuick3DEffect, Effect);
DECLARE_QQ3D_TYPE(QQuick3DShaderUtilsRenderPass, Pass);
DECLARE_QQ3D_TYPE(QQuick3DShaderUtilsShader, Shader);
DECLARE_QQ3D_TYPE(QQuick3DInstanceList, InstanceList);
DECLARE_QQ3D_TYPE(QQuick3DInstanceListEntry, InstanceListEntry);

using QmlTypeNames = QHash<QString, int>;

#define QQ3D_TYPE_ENTRY(TYPE) { TypeInfo<TYPE>::qmlTypeName(), TypeInfo<TYPE>::typeId() }

QmlTypeNames baseTypeMap()
{
    return { QQ3D_TYPE_ENTRY(QQuick3DViewport),
             QQ3D_TYPE_ENTRY(QQuick3DSceneEnvironment),
             QQ3D_TYPE_ENTRY(QQuick3DPrincipledMaterial),
             QQ3D_TYPE_ENTRY(QQuick3DDefaultMaterial),
             QQ3D_TYPE_ENTRY(QQuick3DCustomMaterial),
             QQ3D_TYPE_ENTRY(QQuick3DDirectionalLight),
             QQ3D_TYPE_ENTRY(QQuick3DPointLight),
             QQ3D_TYPE_ENTRY(QQuick3DSpotLight),
             QQ3D_TYPE_ENTRY(QQuick3DTexture),
             QQ3D_TYPE_ENTRY(QQuick3DShaderUtilsTextureInput),
             QQ3D_TYPE_ENTRY(QQuick3DModel),
             QQ3D_TYPE_ENTRY(QQuick3DEffect),
             QQ3D_TYPE_ENTRY(QQuick3DShaderUtilsRenderPass),
             QQ3D_TYPE_ENTRY(QQuick3DShaderUtilsShader),
             QQ3D_TYPE_ENTRY(QQuick3DInstanceList),
             QQ3D_TYPE_ENTRY(QQuick3DInstanceListEntry)
    };
}

Q_GLOBAL_STATIC(QmlTypeNames, s_typeMap)

struct Context
{
    enum class Type
    {
        Application,
        Component
    };

    struct Property {
        enum MemberState : quint8
        {
            Uninitialized,
            Initialized
        };

        QObject *target = nullptr;
        QStringView name;
        int targetType = QMetaType::UnknownType;
        QMetaType::Type type = QMetaType::UnknownType;
        MemberState memberState = Uninitialized;
    };

    template<typename T> using Vector = QVector<T>;
    using InterceptObjDefFunc = bool (*)(const QQmlJS::AST::UiObjectDefinition &, Context &, int &);
    using InterceptObjBinding = bool (*)(const QQmlJS::AST::UiObjectBinding &, Context &, int &);
    using InterceptPublicMember = bool (*)(const QQmlJS::AST::UiPublicMember &, Context &, int &);
    using InterceptCallExpression = bool (*)(const QQmlJS::AST::CallExpression &, Context &, int &);

    QQmlJS::Engine *engine = nullptr;
    QDir workingDir; // aka source directory
    QFileInfo currentFileInfo;

    MaterialParser::SceneData sceneData;
    Property property;

    struct Component
    {
        QObject *ptr = nullptr;
        int type = QMetaType::UnknownType;
    };

    QHash<QStringView, QObject *> identifierMap;
    QHash<QString, Component> components;
    InterceptObjDefFunc interceptODFunc = nullptr;
    InterceptObjBinding interceptOBFunc = nullptr;
    InterceptPublicMember interceptPMFunc = nullptr;
    InterceptCallExpression interceptCallExpr = nullptr;
    Type type = Type::Application;
    bool dbgprint = false;
};

Q_DECLARE_TYPEINFO(Context::Component, Q_PRIMITIVE_TYPE);

namespace BuiltinHelpers {

using ArgumentListView = InvasiveListView<QQmlJS::AST::ArgumentList>;

template <typename T> Q_REQUIRED_RESULT constexpr quint8 componentCount() { Q_STATIC_ASSERT(true); return 0; }
template <> Q_REQUIRED_RESULT constexpr quint8 componentCount<QVector2D>() { return 2; }
template <> Q_REQUIRED_RESULT constexpr quint8 componentCount<QVector3D>() { return 3; }
template <> Q_REQUIRED_RESULT constexpr quint8 componentCount<QVector4D>() { return 4; }

static double expressionValue(const QQmlJS::AST::ExpressionNode &expr) {
    using namespace QQmlJS::AST;

    if (expr.kind == Node::Kind_NumericLiteral) {
        return static_cast<const NumericLiteral &>(expr).value;
    } else if (expr.kind == Node::Kind_UnaryMinusExpression) {
        const auto &minusExpr = static_cast<const UnaryMinusExpression &>(expr);
        if (minusExpr.expression && minusExpr.expression->kind == Node::Kind_NumericLiteral)
            return static_cast<const NumericLiteral &>(*minusExpr.expression).value * -1.0;
    } else if (expr.kind == Node::Kind_UnaryPlusExpression) {
        const auto &plusExpr = static_cast<const UnaryPlusExpression &>(expr);
        if (plusExpr.expression && plusExpr.expression->kind == Node::Kind_NumericLiteral)
            return static_cast<const NumericLiteral &>(*plusExpr.expression).value;
    } else {
        printf("Expression type \'%d\' unhandled!\n", expr.kind);
    }

    return 0.0;
}

template <typename T>
static inline bool setProperty(const Context::Property &property, const T &v)
{
    return property.target->setProperty(property.name.toLatin1(), QVariant::fromValue(v));
}

template<typename Vec>
static Vec toVec(const ArgumentListView &list, bool *ok = nullptr)
{
    using namespace QQmlJS::AST;
    int i = 0;
    const int e = componentCount<Vec>();
    Vec vec;
    for (const auto &listItem : list) {
        if (listItem.expression && i != e)
            vec[i] = expressionValue(*listItem.expression);
        ++i;
    }

    if (ok)
        *ok = (i == e);

    return vec;
}

static QPointF toPoint(const ArgumentListView &list, bool *ok = nullptr)
{
    using namespace QQmlJS::AST;
    int i = 0;
    const int e = 2;
    qreal args[e];
    for (const auto &listItem : list) {
        if (listItem.expression && i != e)
            args[i] = expressionValue(*listItem.expression);
        ++i;
    }

    if (ok)
        *ok = (i == e);

    return QPointF(args[0], args[1]);
}

static QSizeF toSize(const ArgumentListView &list, bool *ok = nullptr)
{
    using namespace QQmlJS::AST;
    int i = 0;
    const int e = 2;
    qreal args[e];
    for (const auto &listItem : list) {
        if (listItem.expression && listItem.expression->kind == Node::Kind_NumericLiteral && i != e)
            args[i] = expressionValue(*listItem.expression);
        ++i;
    }

    if (ok)
        *ok = (i == e);

    return QSizeF(args[0], args[1]);
}

static QRectF toRect(const ArgumentListView &list, bool *ok = nullptr)
{
    using namespace QQmlJS::AST;
    int i = 0;
    const int e = 4;
    qreal args[e];
    for (const auto &listItem : list) {
        if (listItem.expression && i != e)
            args[i] = expressionValue(*listItem.expression);
        ++i;
    }

    if (ok)
        *ok = (i == e);

    return QRectF(args[0], args[1], args[2], args[3]);
}

static QMatrix4x4 toMat44(const ArgumentListView &list, bool *ok = nullptr)
{
    using namespace QQmlJS::AST;
    int i = 0;
    const int e = 16;
    float args[e];
    for (const auto &listItem : list) {
        if (listItem.expression && i != e)
            args[i] = float(expressionValue(*listItem.expression));
        ++i;
    }

    if (ok)
        *ok = (i == e);

    return QMatrix4x4(args);
}

static QQuaternion toQuaternion(const ArgumentListView &list, bool *ok = nullptr)
{
    using namespace QQmlJS::AST;
    int i = 0;
    const int e = 4;
    float args[e];
    for (const auto &listItem : list) {
        if (listItem.expression && listItem.expression->kind == Node::Kind_NumericLiteral && i != e)
            args[i] = float(expressionValue(*listItem.expression));
        ++i;
    }

    if (ok)
        *ok = (i == e);

    return QQuaternion(args[0], args[1], args[2], args[3]);
}

// String variants
// Note: Unlike the call variants we assume arguments are correct (can be converted),
// as they should have failed earlier, during parsing, if they were not.
template <typename Vec>
static Vec toVec(const QStringView &ref)
{
    const auto args = ref.split(u',');
    Vec vec;
    bool ok = false;
    if (args.size() == componentCount<Vec>()) {
        for (int i = 0; i != componentCount<Vec>(); ++i) {
            vec[i] = args.at(i).toDouble(&ok);
            Q_ASSERT(ok);
        }
    }

    return vec;
}

static QPointF toPoint(const QStringView &ref)
{
    const auto args = ref.split(u",");
    if (args.size() == 2) {
        bool ok = false;
        const auto arg0 = args.at(0).toDouble(&ok);
        Q_ASSERT(ok);
        const auto arg1 = args.at(1).toDouble(&ok);
        Q_ASSERT(ok);
        return QPointF(arg0, arg1);
    }
    return QPointF();
}

static QSizeF toSize(const QStringView &ref)
{
    const auto args = ref.split(u'x');
    if (args.size() == 2) {
        bool ok = false;
        const auto arg0 = args.at(0).toDouble(&ok);
        Q_ASSERT(ok);
        const auto arg1 = args.at(1).toDouble(&ok);
        Q_ASSERT(ok);
        return QSizeF(arg0, arg1);
    }
    return QSizeF();
}

static QRectF toRect(const QStringView &ref)
{
    auto args = ref.split(u",");
    if (args.size() == 3) {
        bool ok = false;
        const auto arg0 = args.at(0).toDouble(&ok);
        Q_ASSERT(ok);
        const auto arg1 = args.at(1).toDouble(&ok);
        Q_ASSERT(ok);
        args = args.at(2).split(u'x');
        if (args.size() == 2) {
            const auto arg2 = args.at(0).toDouble(&ok);
            Q_ASSERT(ok);
            const auto arg3 = args.at(1).toDouble(&ok);
            Q_ASSERT(ok);
            return QRectF(arg0, arg1, arg2, arg3);
        }
    }
    return QRectF();
}

static QQuaternion toQuaternion(const QStringView &ref)
{
    const auto args = ref.split(u',');
    if (args.size() == 4) {
        bool ok = false;
        const auto arg0 = args.at(0).toDouble(&ok);
        Q_ASSERT(ok);
        const auto arg1 = args.at(1).toDouble(&ok);
        Q_ASSERT(ok);
        const auto arg2 = args.at(2).toDouble(&ok);
        Q_ASSERT(ok);
        const auto arg3 = args.at(3).toDouble(&ok);
        Q_ASSERT(ok);
        return QQuaternion(arg0, arg1, arg2, arg3);
    }
    return QQuaternion();
}

} // BuiltinHelpers

template <typename T>
static void cloneQmlList(const QObject &so, QMetaProperty &sp, QObject &to, QMetaProperty &tp) {
    Q_ASSERT(sp.typeId() == tp.typeId());
    const auto tv = tp.read(&to);
    const auto sv = sp.read(&so);
    if (sv.isValid() && tv.isValid()) {
        auto tl = tv.value<QQmlListProperty<T>>();
        auto sl = sv.value<QQmlListProperty<T>>();
        const auto count = sl.count(&sl);
        for (int i = 0; count != i; ++i)
            tl.append(&tl, sl.at(&sl, i));
    }
}

static void cloneProperties(QObject &target, const QObject &source)
{
    Q_ASSERT(target.metaObject() == source.metaObject());
    const auto smo = source.metaObject();
    auto tmo = target.metaObject();
    const int propCount = smo->propertyCount();
    for (int i = 0; i != propCount; ++i) {
        auto sp = smo->property(i);
        auto tp = tmo->property(i);
        if (sp.typeId() == tp.typeId()) {
            if (sp.typeId() == TypeInfo<QQuick3DMaterial>::qmlListTypeId())
                cloneQmlList<QQuick3DMaterial>(source, sp, target, tp);
            else if (sp.typeId() == TypeInfo<QQuick3DEffect>::qmlListTypeId())
                cloneQmlList<QQuick3DEffect>(source, sp, target, tp);
            else if (sp.typeId() == TypeInfo<QQuick3DShaderUtilsRenderPass>::qmlListTypeId())
                cloneQmlList<QQuick3DShaderUtilsRenderPass>(source, sp, target, tp);
            else if (sp.typeId() == TypeInfo<QQuick3DShaderUtilsShader>::qmlListTypeId())
                cloneQmlList<QQuick3DShaderUtilsShader>(source, sp, target, tp);
            else
                tmo->property(i).write(&target, smo->property(i).read(&source));
        }
    }

    // Clone the dynamic properties as well
    for (const auto &prop : source.dynamicPropertyNames())
        target.setProperty(prop.constData(), source.property(prop.constData()));
}

template <typename T>
inline QVariant fromStringEnumHelper(const QStringView &ref, const QMetaProperty &property)
{
    bool ok = false;
    const int v = property.enumerator().keyToValue(ref.toLatin1(), &ok);
    return ok ? QVariant::fromValue(T(v)) : QVariant();
}

static QVariant fromString(const QStringView &ref, const Context &ctx)
{
    const auto &p = ctx.property;
    if (!p.target)
        return QVariant();

    static const auto toBuiltinType = [](int type, const QStringView &ref, const QDir &workingDir) {
        using namespace BuiltinHelpers;
        bool ok = false;
        switch (type) {
        case QMetaType::Int:
        {
            const auto v = ref.toInt(&ok);
            return (ok ? QVariant::fromValue(v) : QVariant());
        }
            break;
        case QMetaType::Bool:
        {
            const auto v = ref.toInt(&ok);
            return (ok ? QVariant::fromValue(bool(v)) : QVariant());
        }
        case QMetaType::Double:
        {
            const auto v = ref.toDouble(&ok);
            return (ok ? QVariant::fromValue(qreal(v)) : QVariant());
        }
            break;
        case QMetaType::QString:
            return QVariant::fromValue(ref);
        case QMetaType::QUrl:
        {
            if (ref.startsWith(u':') || ref.startsWith(QDir::separator()))
                return QVariant::fromValue(QUrl::fromLocalFile(ref.toString()));
            else if (ref.startsWith(u'#'))
                return QVariant::fromValue(QUrl(ref.toString()));
            else
                return QVariant::fromValue(QUrl::fromUserInput(ref.toString(), workingDir.canonicalPath()));
        }
        case QMetaType::QColor:
            return QVariant::fromValue(QColor(ref));
        case QMetaType::QTime:
            return QVariant::fromValue(QTime::fromString(ref.toString()));
        case QMetaType::QDate:
            return QVariant::fromValue(QDate::fromString(ref.toString()));
        case QMetaType::QDateTime:
            return QVariant::fromValue(QDateTime::fromString(ref.toString()));
        case QMetaType::QRectF:
            return QVariant::fromValue(toRect(ref));
        case QMetaType::QPointF:
            return QVariant::fromValue(toPoint(ref));
        case QMetaType::QSizeF:
            return QVariant::fromValue(toSize(ref));
        case QMetaType::QVector2D:
            return QVariant::fromValue(toVec<QVector2D>(ref));
        case QMetaType::QVector3D:
            return QVariant::fromValue(toVec<QVector3D>(ref));
        case QMetaType::QVector4D:
            return QVariant::fromValue(toVec<QVector4D>(ref));
        case QMetaType::QQuaternion:
            return QVariant::fromValue(toQuaternion(ref));
        }

        return QVariant();
    };

    if (p.type != QMetaType::UnknownType) // Built in Qt types int, vector3d etc
        return toBuiltinType(p.type, ref, ctx.workingDir);

    // hard mode, detect the property type
    // We only care about the types that are relevant for us
    if (p.targetType != QMetaType::UnknownType) {
        Q_ASSERT(p.target);
        Q_ASSERT(!p.name.isEmpty());
        const int idx = p.target->metaObject()->indexOfProperty(p.name.toLatin1().constData());
        const auto property = p.target->metaObject()->property(idx);
        if (property.metaType().id() >= QMetaType::User) {
            const QMetaType metaType = property.metaType();
            if (p.targetType == TypeInfo<QQuick3DDefaultMaterial>::typeId() || p.targetType == TypeInfo<QQuick3DPrincipledMaterial>::typeId()) {
                // Common for both materials
                if (metaType.id() == qMetaTypeId<QQuick3DMaterial::CullMode>())
                    return fromStringEnumHelper<QQuick3DMaterial::CullMode>(ref, property);
                if (metaType.id() == qMetaTypeId<QQuick3DMaterial::TextureChannelMapping>())
                    return fromStringEnumHelper<QQuick3DMaterial::TextureChannelMapping>(ref, property);

                if (p.targetType == TypeInfo<QQuick3DPrincipledMaterial>::typeId()) {
                    if (metaType.id() == qMetaTypeId<QQuick3DPrincipledMaterial::Lighting>())
                        return fromStringEnumHelper<QQuick3DPrincipledMaterial::Lighting>(ref, property);
                    if (metaType.id() == qMetaTypeId<QQuick3DPrincipledMaterial::BlendMode>())
                        return fromStringEnumHelper<QQuick3DPrincipledMaterial::BlendMode>(ref, property);
                    if (metaType.id() == qMetaTypeId<QQuick3DPrincipledMaterial::AlphaMode>())
                        return fromStringEnumHelper<QQuick3DPrincipledMaterial::AlphaMode>(ref, property);
                } else if (p.targetType == TypeInfo<QQuick3DDefaultMaterial>::typeId()) {
                    if (metaType.id() == qMetaTypeId<QQuick3DDefaultMaterial::Lighting>())
                        return fromStringEnumHelper<QQuick3DDefaultMaterial::Lighting>(ref, property);
                    if (metaType.id() == qMetaTypeId<QQuick3DDefaultMaterial::BlendMode>())
                        return fromStringEnumHelper<QQuick3DDefaultMaterial::BlendMode>(ref, property);
                    if (metaType.id() == qMetaTypeId<QQuick3DDefaultMaterial::SpecularModel>())
                        return fromStringEnumHelper<QQuick3DDefaultMaterial::SpecularModel>(ref, property);
                }
            } else if (p.targetType == TypeInfo<QQuick3DCustomMaterial>::typeId()) {
                if (metaType.id() == qMetaTypeId<QQuick3DCustomMaterial::ShadingMode>())
                    return fromStringEnumHelper<QQuick3DCustomMaterial::ShadingMode>(ref, property);
                if (metaType.id() == qMetaTypeId<QQuick3DCustomMaterial::BlendMode>())
                    return fromStringEnumHelper<QQuick3DCustomMaterial::BlendMode>(ref, property);
            } else if (p.targetType == TypeInfo<QQuick3DSpotLight>::typeId() || p.targetType == TypeInfo<QQuick3DPointLight>::typeId()) {
                if (metaType.id() == qMetaTypeId<QQuick3DAbstractLight::QSSGShadowMapQuality>())
                    return fromStringEnumHelper<QQuick3DAbstractLight::QSSGShadowMapQuality>(ref, property);
            } else if (p.targetType == TypeInfo<QQuick3DSceneEnvironment>::typeId()) {
                if (metaType.id() == qMetaTypeId<QQuick3DSceneEnvironment::QQuick3DEnvironmentBackgroundTypes>())
                    return fromStringEnumHelper<QQuick3DSceneEnvironment::QQuick3DEnvironmentBackgroundTypes>(ref, property);
                if (metaType.id() == qMetaTypeId<QQuick3DSceneEnvironment::QQuick3DEnvironmentAAModeValues>())
                    return fromStringEnumHelper<QQuick3DSceneEnvironment::QQuick3DEnvironmentAAModeValues>(ref, property);
                if (metaType.id() == qMetaTypeId<QQuick3DSceneEnvironment::QQuick3DEnvironmentAAQualityValues>())
                    return fromStringEnumHelper<QQuick3DSceneEnvironment::QQuick3DEnvironmentAAQualityValues>(ref, property);
                if (metaType.id() == qMetaTypeId<QQuick3DSceneEnvironment::QQuick3DEnvironmentTonemapModes>())
                    return fromStringEnumHelper<QQuick3DSceneEnvironment::QQuick3DEnvironmentTonemapModes>(ref, property);
            } else if (p.targetType == TypeInfo<QQuick3DShaderUtilsShader>::typeId()) {
                if (metaType.id() == qMetaTypeId<QQuick3DShaderUtilsShader::Stage>())
                    return fromStringEnumHelper<QQuick3DShaderUtilsShader::Stage>(ref, property);
            }
        } else { // Qt type
            return toBuiltinType(property.metaType().id(), ref, ctx.workingDir);
        }
    }

    if (ctx.dbgprint)
        printf("Unhandled type for property %s\n", ref.toLatin1().constData());

    return QVariant();
}

static QString getQmlFileExtension() { return QStringLiteral("qml"); }

struct Visitors
{
    static void visit(const QQmlJS::AST::UiProgram &program, Context &ctx, int &ret)
    {
        using namespace QQmlJS::AST;
        const bool readHeaders = false;
        if (readHeaders && program.headers) { // No real need for us to look at the includes
            using HeaderItem = UiHeaderItemList;
            using Headers = InvasiveListView<HeaderItem>;

            Headers headers(*program.headers);
            for (const auto &header : headers)
                printf("Type: %d\n", header.kind);
        }
        if (program.members)
            visit(*program.members, ctx, ret);
    }
    static void visit(const QQmlJS::AST::UiObjectInitializer &objInitializer, Context &ctx, int &ret)
    {
        using namespace QQmlJS::AST;
        if (objInitializer.members)
            visit(*objInitializer.members, ctx, ret);
    }

    static void visit(const QQmlJS::AST::UiObjectDefinition &def, Context &ctx, int &ret)
    {
        using namespace QQmlJS::AST;
        if (ctx.dbgprint)
            printf("Object definition -> %s\n", def.qualifiedTypeNameId->name.toLocal8Bit().constData());
        if (!(ctx.interceptODFunc && ctx.interceptODFunc(def, ctx, ret))) {
            if (def.initializer)
                visit(*static_cast<UiObjectInitializer *>(def.initializer), ctx, ret);
        }
    }

    static void visit(const QQmlJS::AST::UiArrayMemberList &memberList, Context &ctx, int &ret)
    {
        using namespace QQmlJS::AST;
        using ArrayMemberItem = UiArrayMemberList;
        using ArrayMembers = InvasiveListView<ArrayMemberItem>;

        ArrayMembers arrayMembers(memberList);
        for (auto &object : arrayMembers) {
            if (object.member->kind == Node::Kind_UiObjectDefinition) {
                const auto &def = *static_cast<UiObjectDefinition *>(object.member);
                visit(def, ctx, ret);
            }
        }
    }

    static void visit(const QQmlJS::AST::UiScriptBinding &binding, Context &ctx, int &ret)
    {
        using namespace QQmlJS::AST;
        if (ctx.dbgprint)
            printf("Script binding -> %s ", binding.qualifiedId->name.toLocal8Bit().constData());

        const auto oldName = ctx.property.name; // reentrancy
        ctx.property.name = binding.qualifiedId->name;

        if (binding.statement) {
            if (binding.statement->kind == Node::Kind_ExpressionStatement) {
                const auto &expressionStatement = static_cast<const ExpressionStatement &>(*binding.statement);
                visit(expressionStatement, ctx, ret);
            }
        }
        ctx.property.name = oldName;
    }

    static void visit(const QQmlJS::AST::UiArrayBinding &arrayBinding, Context &ctx, int &ret)
    {
        using namespace QQmlJS::AST;
        if (ctx.dbgprint)
            printf("Array binding(s) -> %s: [\n", arrayBinding.qualifiedId->name.toLocal8Bit().constData());

        const auto oldName = ctx.property.name; // reentrancy
        ctx.property.name = arrayBinding.qualifiedId->name;

        if (arrayBinding.members)
            visit(*arrayBinding.members, ctx, ret);

        if (ctx.dbgprint)
            printf("]\n");

        ctx.property.name = oldName;
    }

    static void visit(const QQmlJS::AST::UiObjectBinding &objectBinding, Context &ctx, int &ret)
    {
        using namespace QQmlJS::AST;

        if (ctx.dbgprint)
            printf("Object binding -> %s: %s {\n", objectBinding.qualifiedId->name.toLocal8Bit().constData(), objectBinding.qualifiedTypeNameId->name.toLocal8Bit().constData());

        if (objectBinding.initializer) {
            if (!(ctx.interceptOBFunc && ctx.interceptOBFunc(objectBinding, ctx, ret)))
                visit(*objectBinding.initializer, ctx, ret);
        }

        if (ctx.dbgprint)
            printf("}\n");
    }

    static void visit(const QQmlJS::AST::UiPublicMember &member, Context &ctx, int &ret)
    {
        using namespace QQmlJS::AST;

        if (ctx.dbgprint)
            printf("%s member -> %s ", (member.type == UiPublicMember::Signal ? "Signal" : "Property"), member.name.toLocal8Bit().constData());

        auto name = ctx.property.name;
        ctx.property.name = member.name;
        const auto typeCpy = ctx.property.type;

        if (!(ctx.interceptPMFunc && ctx.interceptPMFunc(member, ctx, ret))) {
            if (member.statement) {
                const auto &statement = member.statement;
                if (statement->kind == Node::Kind_ExpressionStatement)
                    visit(static_cast<const ExpressionStatement &>(*statement), ctx, ret);
                else if (ctx.dbgprint)
                    printf("Unhandled statement (%d)\n", statement->kind);
            } else if (member.binding) {
                const auto &binding = member.binding;
                if (binding->kind == Node::Kind_UiObjectBinding)
                    visit(static_cast<const UiObjectBinding &>(*binding), ctx, ret);
                else if (ctx.dbgprint)
                    printf("Unhandled binding (%d)\n", binding->kind);
            }
        }

        qSwap(ctx.property.name, name);
        ctx.property.type = typeCpy;
    }

    static void visit(const QQmlJS::AST::ExpressionStatement &exprStatement, Context &ctx, int &ret)
    {
        using namespace QQmlJS::AST;
        if (exprStatement.expression) {
            if (exprStatement.expression->kind == Node::Kind_IdentifierExpression) {
                const auto &identExpression = static_cast<const IdentifierExpression &>(*exprStatement.expression);
                visit(identExpression, ctx, ret);
            } else if (exprStatement.expression->kind == Node::Kind_StringLiteral) {
                const auto &stringLiteral = static_cast<const StringLiteral &>(*exprStatement.expression);
                visit(stringLiteral, ctx, ret);
            } else if (exprStatement.expression->kind == Node::Kind_NumericLiteral) {
                const auto &numericLiteral = static_cast<const NumericLiteral &>(*exprStatement.expression);
                visit(numericLiteral, ctx, ret);
            } else if (exprStatement.expression->kind == Node::Kind_FieldMemberExpression) {
                const auto &fieldMemberExpression = static_cast<const FieldMemberExpression &>(*exprStatement.expression);
                visit(fieldMemberExpression, ctx, ret);
            } else if (exprStatement.expression->kind == Node::Kind_TrueLiteral || exprStatement.expression->kind == Node::Kind_FalseLiteral) {
                const bool v = (exprStatement.expression->kind == Node::Kind_TrueLiteral);
                if (ctx.dbgprint)
                    printf("-> TrueLiteral: %s\n", v ? "true" : "false");
                if (ctx.property.target) {
                    auto target = ctx.property.target;
                    const auto &name = ctx.property.name;
                    target->setProperty(name.toLatin1(), QVariant::fromValue(v));
                }
            } else if (exprStatement.expression->kind == Node::Kind_ArrayPattern) {
                const auto &arrayPattern = static_cast<const ArrayPattern &>(*exprStatement.expression);
                visit(arrayPattern, ctx, ret);
            } else if (exprStatement.expression->kind == Node::Kind_CallExpression) {
                const auto &callExpression = static_cast<const CallExpression &>(*exprStatement.expression);
                visit(callExpression, ctx, ret);
            } else if (exprStatement.expression->kind == Node::Kind_UnaryMinusExpression) {
                const auto &unaryMinusExpr = static_cast<const UnaryMinusExpression &>(*exprStatement.expression);
                if (unaryMinusExpr.expression && unaryMinusExpr.expression->kind == Node::Kind_NumericLiteral) {
                    auto &numericLiteral = static_cast<NumericLiteral &>(*unaryMinusExpr.expression);
                    const auto value = numericLiteral.value;
                    numericLiteral.value *= -1;
                    visit(numericLiteral, ctx, ret);
                    numericLiteral.value = value;
                }
            } else if (exprStatement.expression->kind == Node::Kind_UnaryPlusExpression) {
                const auto &unaryPlusExpr = static_cast<const UnaryPlusExpression &>(*exprStatement.expression);
                if (unaryPlusExpr.expression)
                    visit(static_cast<const NumericLiteral &>(*unaryPlusExpr.expression), ctx, ret);
            } else {
                if (ctx.dbgprint)
                    printf("<expression: %d>\n", exprStatement.expression->kind);
            }
        }
    }

    static void visit(const QQmlJS::AST::IdentifierExpression &idExpr, Context &ctx, int &ret)
    {
        Q_UNUSED(ret);
        if (ctx.dbgprint)
            printf("-> Identifier: %s\n", idExpr.name.toLocal8Bit().constData());

        if (ctx.property.target && ctx.type != Context::Type::Component) {
            const auto foundIt = ctx.identifierMap.constFind(idExpr.name);
            const auto end = ctx.identifierMap.constEnd();
            if (foundIt != end) { // If an item was found it means this is a reference
                if (ctx.property.targetType == TypeInfo<QQuick3DModel>::typeId()) {
                    if (QQuick3DMaterial *mat = qobject_cast<QQuick3DMaterial *>(*foundIt)) {
                        auto materials = qobject_cast<QQuick3DModel *>(ctx.property.target)->materials();
                        // Since we are initializing this for the first time, make sure we clean out any inherited data!
                        if (ctx.property.memberState == Context::Property::Uninitialized) {
                            if (ctx.dbgprint)
                                printf("Clearing inherited materials\n");
                            materials.clear(&materials);
                            ctx.property.memberState = Context::Property::Initialized;
                        }
                        materials.append(&materials, mat);
                        if (ctx.dbgprint)
                            printf("Appending material to %s\n", ctx.property.name.toLatin1().constData());
                    } else if (QQuick3DInstanceList *instancingList = qobject_cast<QQuick3DInstanceList *>(*foundIt)) {
                        qobject_cast<QQuick3DModel *>(ctx.property.target)->setInstancing(instancingList);
                        if (ctx.dbgprint)
                            printf("Setting instance list on model\n");
                    }
                } else if (ctx.property.targetType == TypeInfo<QQuick3DSceneEnvironment>::typeId()) {
                    if (QQuick3DEffect *effect = qobject_cast<QQuick3DEffect *>(*foundIt)) {
                        auto effects = qobject_cast<QQuick3DSceneEnvironment *>(ctx.property.target)->effects();
                        // Since we are initializing this for the first time, make sure we clean out any inherited data!
                        if (ctx.property.memberState == Context::Property::Uninitialized) {
                            if (ctx.dbgprint)
                                printf("Clearing inherited effects\n");
                            effects.clear(&effects);
                            ctx.property.memberState = Context::Property::Initialized;
                        }
                        effects.append(&effects, effect);
                        if (ctx.dbgprint)
                            printf("Appending effect to \'%s\'\n", ctx.property.name.toLatin1().constData());
                    }
                } else if (ctx.property.targetType == TypeInfo<QQuick3DShaderUtilsRenderPass>::typeId()) {
                    if (QQuick3DShaderUtilsShader *shader = qobject_cast<QQuick3DShaderUtilsShader *>(*foundIt)) {
                        auto shaders = qobject_cast<QQuick3DShaderUtilsRenderPass *>(ctx.property.target)->shaders();
                        // Since we are initializing this for the first time, make sure we clean out any inherited data!
                        if (ctx.property.memberState == Context::Property::Uninitialized) {
                            if (ctx.dbgprint)
                                printf("Clearing inherited shaders\n");
                            shaders.clear(&shaders);
                            ctx.property.memberState = Context::Property::Initialized;
                        }
                        shaders.append(&shaders, shader);
                        if (ctx.dbgprint)
                            printf("Appending shader to \'%s\'\n", ctx.property.name.toLatin1().constData());
                    }
                } else if (ctx.property.targetType == TypeInfo<QQuick3DInstanceList>::typeId()) {
                    if (QQuick3DInstanceListEntry *listEntry = qobject_cast<QQuick3DInstanceListEntry *>(*foundIt)) {
                        auto instances = qobject_cast<QQuick3DInstanceList *>(ctx.property.target)->instances();
                        // Since we are initializing this for the first time, make sure we clean out any inherited data!
                        if (ctx.property.memberState == Context::Property::Uninitialized) {
                            if (ctx.dbgprint)
                                printf("Clearing inherited instances\n");
                            instances.clear(&instances);
                            ctx.property.memberState = Context::Property::Initialized;
                        }
                        instances.append(&instances, listEntry);
                        if (ctx.dbgprint)
                            printf("Appending instance entry to %s\n", ctx.property.name.toLatin1().constData());
                    } else if (QQuick3DInstanceList *instancingList = qobject_cast<QQuick3DInstanceList *>(*foundIt)) {
                        qobject_cast<QQuick3DModel *>(ctx.property.target)->setInstancing(instancingList);
                        if (ctx.dbgprint)
                            printf("Setting instance list on model\n");
                    }
                } else if (ctx.dbgprint) {
                    printf("Unhandled binding: %s\n", idExpr.name.toLatin1().constData());
                }
            } else {
                // If no item with 'this' id was found, then that id is for 'this' object (if this not the case, then something is broken, e.g., a ref to an unknown item).
                // NOTE: This can be a problem in the future and we might need to add some more guards, but for now it just won't generate the correct shader(s).
                ctx.identifierMap.insert(idExpr.name, ctx.property.target);
            }
        }
    }

    static void visit(const QQmlJS::AST::StringLiteral &stringLiteral, Context &ctx, int &ret)
    {
        Q_UNUSED(ret);
        if (ctx.dbgprint)
            printf("-> StringLiteral: \"%s\"\n", stringLiteral.value.toLocal8Bit().constData());

        if (ctx.property.target) {
            const auto &name = ctx.property.name;
            const auto v = fromString(stringLiteral.value, ctx);
            if (v.isValid()) {
                const bool b = ctx.property.target->setProperty(name.toLatin1(), v);
                if (b && ctx.dbgprint)
                    printf("Property %s updated!\n", name.toLatin1().constData());
            }
        }
    }

    static void visit(const QQmlJS::AST::NumericLiteral &numericLiteral, Context &ctx, int &ret)
    {
        Q_UNUSED(ret);
        if (ctx.dbgprint)
            printf("-> NumericLiteral: %f\n", numericLiteral.value);

        if (ctx.property.target) {
            auto target = ctx.property.target;
            const auto &name = ctx.property.name;
            target->setProperty(name.toLatin1(), QVariant::fromValue(numericLiteral.value));
        }
    }

    static void visit(const QQmlJS::AST::FieldMemberExpression &fieldMemberExpression, Context &ctx, int &ret)
    {
        using namespace QQmlJS::AST;

        Q_UNUSED(ret);
        if (ctx.dbgprint)
            printf("-> FieldMemberExpression: %s\n", fieldMemberExpression.name.toLocal8Bit().constData());

        if (ctx.property.target) {
            const auto &name = ctx.property.name;
            const auto v = fromString(fieldMemberExpression.name, ctx);
            if (v.isValid())
                ctx.property.target->setProperty(name.toLatin1(), v);
        }
    }

    static void visit(const QQmlJS::AST::ArrayPattern &arrayPattern, Context &ctx, int &ret)
    {
        Q_UNUSED(ret);
        if (ctx.dbgprint)
            printf("-> [ ");

        using namespace QQmlJS::AST;
        using PatternElementItem = PatternElementList;
        using PatternElementListView = InvasiveListView<PatternElementItem>;

        PatternElementListView elements(*arrayPattern.elements);
        for (auto &element : elements) {
            auto patternElement = element.element;
            if (patternElement->type == PatternElement::Literal) {
                if (patternElement->initializer && patternElement->initializer->kind == Node::Kind_IdentifierExpression) {
                    const auto &identExpression = static_cast<const IdentifierExpression &>(*patternElement->initializer);
                    visit(identExpression, ctx, ret);
                }
            } else if (ctx.dbgprint) {
                printf("Unahandled(%d), ", patternElement->type);
            }
        }

        if (ctx.dbgprint)
            printf(" ]\n");

    }

    static void visit(const QQmlJS::AST::CallExpression &callExpression, Context &ctx, int &ret)
    {
        using namespace QQmlJS::AST;

        Q_UNUSED(ret);
        Q_UNUSED(callExpression);
        if (ctx.dbgprint)
            printf("-> Call(%d)\n", callExpression.base->kind);

        (ctx.interceptCallExpr && ctx.interceptCallExpr(callExpression, ctx, ret));
    }

    static void visit(const QQmlJS::AST::UiObjectMember &member, Context &ctx, int &ret)
    {
        using namespace QQmlJS::AST;

        if (member.kind == Node::Kind_UiObjectBinding)
            visit(static_cast<const UiObjectBinding &>(member), ctx, ret);
        else if (ctx.dbgprint)
            printf("Unhandled member (%d)\n", member.kind);
    }

    static void visit(const QQmlJS::AST::UiObjectMemberList &memberList, Context &ctx, int &ret)
    {
        using namespace QQmlJS::AST;
        using ObjectMemberItem = UiObjectMemberList;
        using ObjectMembers = InvasiveListView<ObjectMemberItem>;

        const auto oldEvalType = ctx.property.memberState;

        ObjectMembers objectMembers(memberList);
        for (const auto &member : objectMembers) {
            if (member.member) {
                if (member.member->kind == Node::Kind_UiScriptBinding) {
                    ctx.property.memberState = Context::Property::MemberState::Uninitialized;
                    const auto &scriptBinding = static_cast<const UiScriptBinding &>(*member.member);
                    visit(scriptBinding, ctx, ret);
                } else if (member.member->kind == Node::Kind_UiArrayBinding) {
                    ctx.property.memberState = Context::Property::MemberState::Uninitialized;
                    const auto &arrayBinding = static_cast<const UiArrayBinding &>(*member.member);
                    visit(arrayBinding, ctx, ret);
                } else if (member.member->kind == Node::Kind_UiObjectDefinition) {
                    const auto &objectDef = static_cast<const UiObjectDefinition &>(*member.member);
                    visit(objectDef, ctx, ret);
                } else if (member.member->kind == Node::Kind_UiObjectBinding) {
                    ctx.property.memberState = Context::Property::MemberState::Uninitialized;
                    const auto &objBinding = static_cast<const UiObjectBinding &>(*member.member);
                    visit(objBinding, ctx, ret);
                } else if (member.member->kind == Node::Kind_UiPublicMember) {
                    ctx.property.memberState = Context::Property::MemberState::Uninitialized;
                    const auto &pubMember = static_cast<const UiPublicMember &>(*member.member);
                    visit(pubMember, ctx, ret);
                } else {
                    if (ctx.dbgprint)
                        printf("<member %d>\n", member.member->kind);
                }
            }
        }

        ctx.property.memberState = oldEvalType;
    }

private:
    Visitors() = delete;
    Q_DISABLE_COPY(Visitors);
};

template <typename O, typename T>
T *buildType(const O &obj, Context &ctx, int &ret, const T *base = nullptr)
{
    // swap -> reentrancy
    Context::Property property;
    qSwap(property, ctx.property);
    Q_ASSERT(ctx.property.target == nullptr);

    T *instance = nullptr;

    if (ctx.dbgprint)
        printf("Building %s!\n", TypeInfo<T>::qmlTypeName());

    if (obj.initializer) {
        instance = new T;
        if (base)
            cloneProperties(*instance, *base);

        if (obj.initializer) {
            ctx.property.target = instance;
            ctx.property.targetType = TypeInfo<T>::typeId();
            Visitors::visit(*obj.initializer, ctx, ret);
        }
    }

    // swap back
    qSwap(property, ctx.property);

    return instance;
}

static QQuick3DAbstractLight *buildLight(const QQmlJS::AST::UiObjectDefinition &def,
                                         Context &ctx,
                                         int &ret,
                                         int lightType,
                                         const QQuick3DAbstractLight *base = nullptr)
{
    if (lightType == TypeInfo<QQuick3DDirectionalLight>::typeId())
        return buildType(def, ctx, ret, qobject_cast<const QQuick3DDirectionalLight *>(base));
    if (lightType == TypeInfo<QQuick3DPointLight>::typeId())
        return buildType(def, ctx, ret, qobject_cast<const QQuick3DPointLight *>(base));
    if (lightType == TypeInfo<QQuick3DSpotLight>::typeId())
        return buildType(def, ctx, ret, qobject_cast<const QQuick3DSpotLight *>(base));
    return nullptr;
}


template <typename T>
static void updateProperty(Context &ctx, T type, QStringView propName)
{
    if (ctx.property.target) {
        if (ctx.dbgprint)
            printf("Updating property %s\n", propName.toLatin1().constData());
        const auto &target = ctx.property.target;
        if (ctx.property.memberState == Context::Property::Uninitialized) {
            target->setProperty(propName.toLatin1().constData(), QVariant::fromValue(type));
            ctx.property.memberState = Context::Property::Initialized;
        } else {
            const int idx = target->metaObject()->indexOfProperty(propName.toLatin1().constData());
            if (idx != -1) {
                auto prop = target->metaObject()->property(idx);
                prop.write(target, QVariant::fromValue(type));
            }
        }
    }
}

static bool interceptObjectBinding(const QQmlJS::AST::UiObjectBinding &objectBinding, Context &ctx, int &ret)
{
    if (ctx.dbgprint)
        printf("Intercepted object binding!\n");

    bool handled = false;

    const auto &typeName = objectBinding.qualifiedTypeNameId->name.toString();
    const auto &propName = objectBinding.qualifiedId->name;

    int type = -1;

    // Base type?
    const auto typeIt = s_typeMap->constFind(typeName);
    if (typeIt != s_typeMap->cend())
        type = *typeIt;

    // Component?
    auto &components = ctx.components;
    const auto compIt = (type == -1) ? components.constFind(typeName) : components.cend();
    QObject *base = nullptr;
    if (compIt != components.cend()) {
        type = compIt->type;
        base = compIt->ptr;
    }

    if (type != -1) {
        if (ctx.dbgprint)
            printf("Resolving: \'%s\'\n", qPrintable(typeName));

        if (type == TypeInfo<QQuick3DSceneEnvironment>::typeId()) {
            if (ctx.property.targetType == TypeInfo<QQuick3DViewport>::typeId()) {
                if (auto environment = buildType(objectBinding, ctx, ret, qobject_cast<QQuick3DSceneEnvironment *>(base))) {
                    auto viewport = qobject_cast<QQuick3DViewport *>(ctx.property.target);
                    Q_ASSERT(viewport);
                    viewport->setEnvironment(environment);
                    handled = true;
                }
            }
        } else if (type == TypeInfo<QQuick3DTexture>::typeId()) {
            if (auto tex = buildType(objectBinding, ctx, ret, qobject_cast<QQuick3DTexture *>(base))) {
                updateProperty(ctx, tex, propName);
                ctx.sceneData.textures.append(tex);
            }
            handled = true;
        } else if (type == TypeInfo<QQuick3DShaderUtilsTextureInput>::typeId()) {
            auto texInput = buildType(objectBinding, ctx, ret, qobject_cast<QQuick3DShaderUtilsTextureInput *>(base));
            if (texInput && texInput->texture()) {
                updateProperty(ctx, texInput, propName);
                ctx.sceneData.textures.append(texInput->texture());
            }
            handled = true;
        } else if (type == TypeInfo<QQuick3DEffect>::typeId()) {
            if (ctx.property.targetType == TypeInfo<QQuick3DSceneEnvironment>::typeId()) {
                if (auto effect = buildType(objectBinding, ctx, ret, qobject_cast<QQuick3DEffect *>(base))) {
                    auto sceneEnvironment = qobject_cast<QQuick3DSceneEnvironment *>(ctx.property.target);
                    Q_ASSERT(sceneEnvironment);
                    auto effects = sceneEnvironment->effects();
                    effects.append(&effects, effect);
                    handled = true;
                }
            }
        } else if (type == TypeInfo<QQuick3DShaderUtilsRenderPass>::typeId()) {
            if (ctx.property.targetType == TypeInfo<QQuick3DEffect>::typeId()) {
                if (auto pass = buildType(objectBinding, ctx, ret, qobject_cast<QQuick3DShaderUtilsRenderPass *>(base))) {
                    auto effect = qobject_cast<QQuick3DEffect *>(ctx.property.target);
                    Q_ASSERT(effect);
                    auto passes = effect->passes();
                    passes.append(&passes, pass);
                    handled = true;
                }
            }
        } else if (type == TypeInfo<QQuick3DShaderUtilsShader>::typeId()) {
            if (ctx.property.targetType == TypeInfo<QQuick3DShaderUtilsRenderPass>::typeId()) {
                if (auto shader = buildType(objectBinding, ctx, ret, qobject_cast<QQuick3DShaderUtilsShader *>(base))) {
                    auto pass = qobject_cast<QQuick3DShaderUtilsRenderPass *>(ctx.property.target);
                    Q_ASSERT(pass);
                    auto shaders = pass->shaders();
                    shaders.append(&shaders, shader);
                    handled = true;
                }
            }
        } else if (type == TypeInfo<QQuick3DDefaultMaterial>::typeId()) {
            if (ctx.property.targetType == TypeInfo<QQuick3DModel>::typeId()) {
                if (auto mat = buildType(objectBinding, ctx, ret, qobject_cast<QQuick3DDefaultMaterial *>(base))) {
                    auto model = qobject_cast<QQuick3DModel *>(ctx.property.target);
                    Q_ASSERT(model);
                    auto materials = model->materials();
                    materials.append(&materials, mat);
                    handled = true;
                    if (ctx.dbgprint)
                        printf("Appending material to %s\n", ctx.property.name.toLatin1().constData());
                }
            }
        } else if (type == TypeInfo<QQuick3DPrincipledMaterial>::typeId()) {
            if (ctx.property.targetType == TypeInfo<QQuick3DModel>::typeId()) {
                if (auto mat = buildType(objectBinding, ctx, ret, qobject_cast<QQuick3DPrincipledMaterial *>(base))) {
                    auto model = qobject_cast<QQuick3DModel *>(ctx.property.target);
                    Q_ASSERT(model);
                    auto materials = model->materials();
                    materials.append(&materials, mat);
                    handled = true;
                }
            }
        } else if (type == TypeInfo<QQuick3DCustomMaterial>::typeId()) {
            if (ctx.property.targetType == TypeInfo<QQuick3DModel>::typeId()) {
                if (auto mat = buildType(objectBinding, ctx, ret, qobject_cast<QQuick3DCustomMaterial *>(base))) {
                    auto model = qobject_cast<QQuick3DModel *>(ctx.property.target);
                    Q_ASSERT(model);
                    auto materials = model->materials();
                    materials.append(&materials, mat);
                    handled = true;
                }
            }
        } else if (ctx.dbgprint) {
            printf("Unhandled type\n");
        }
    }

    return handled;
}

static bool interceptObjectDef(const QQmlJS::AST::UiObjectDefinition &def, Context &ctx, int &ret)
{
    const auto &typeName = def.qualifiedTypeNameId->name.toString();

    if (ctx.dbgprint)
        printf("Intercepted object definition (\'%s\')!\n", typeName.toLatin1().constData());

    QString componentName;
    int type = -1;
    bool doRegisterComponent = false;

    // Base type?
    const auto typeIt = s_typeMap->constFind(typeName);
    if (typeIt != s_typeMap->cend())
        type = *typeIt;

    // Component?
    auto &components = ctx.components;
    const auto compIt = (type == -1) ? components.constFind(typeName) : components.cend();
    if (compIt != components.cend())
        type = compIt->type;

    // If this is a new component register it
    if (ctx.type == Context::Type::Component && ctx.property.target == nullptr && type != -1) {
        const auto &fileName = ctx.currentFileInfo.fileName();
        componentName = fileName.left(fileName.size() - 4);
        doRegisterComponent = !componentName.isEmpty();
    }

    const auto registerComponent = [&ctx, &components, &componentName](Context::Component component) {
        if (ctx.dbgprint)
            printf("Registering component \'%s\'\n", qPrintable(componentName));
        components.insert(componentName, component);
    };

    if (type == TypeInfo<QQuick3DViewport>::typeId()) {
        const QQuick3DViewport *base = (compIt != components.cend()) ? qobject_cast<QQuick3DViewport *>(compIt->ptr) : nullptr;
        if (QQuick3DViewport *viewport = buildType(def, ctx, ret, base)) {
            // If this is a component we'll store it for lookups later.
            if (doRegisterComponent)
                registerComponent({ viewport, type });
            // Only one viewport supported atm (see SceneEnvironment case as well).
            if (!ctx.sceneData.viewport)
                ctx.sceneData.viewport = viewport;
        }
    } else if (type == TypeInfo<QQuick3DSceneEnvironment>::typeId()) {
        const QQuick3DSceneEnvironment *base = (compIt != components.cend()) ? qobject_cast<QQuick3DSceneEnvironment *>(compIt->ptr) : nullptr;
        if (QQuick3DSceneEnvironment *sceneEnv = buildType(def, ctx, ret, base)) {
            // If this is a component we'll store it for lookups later.
            if (doRegisterComponent)
                registerComponent({ sceneEnv, type });

            if (ctx.sceneData.viewport)
                ctx.sceneData.viewport->setEnvironment(sceneEnv);
        }
    } else if (type == TypeInfo<QQuick3DPrincipledMaterial>::typeId()) {
        const QQuick3DPrincipledMaterial *base = (compIt != components.cend()) ? qobject_cast<QQuick3DPrincipledMaterial *>(compIt->ptr) : nullptr;
        if (QQuick3DPrincipledMaterial *mat = buildType(def, ctx, ret, base)) {
            // If this is a component we'll store it for lookups later.
            if (doRegisterComponent)
                registerComponent({ mat, type });

            if (ctx.property.target) {
                if (ctx.property.targetType == TypeInfo<QQuick3DModel>::typeId()) {
                    auto materials = qobject_cast<QQuick3DModel *>(ctx.property.target)->materials();
                    if (ctx.property.memberState == Context::Property::Uninitialized) {
                        if (ctx.dbgprint)
                            printf("Clearing inherited materials\n");
                        materials.clear(&materials);
                        ctx.property.memberState = Context::Property::Initialized;
                    }
                    materials.append(&materials, mat);
                    if (ctx.dbgprint)
                        printf("Appending material to %s\n", ctx.property.name.toLatin1().constData());
                }
            }

            // At this point we don't know if this material is going to be referenced somewhere else, so keep it in the list
            ctx.sceneData.materials.push_back(mat);
        }
    } else if (type == TypeInfo<QQuick3DDefaultMaterial>::typeId()) {
        const QQuick3DDefaultMaterial *base = (compIt != components.cend()) ? qobject_cast<QQuick3DDefaultMaterial *>(compIt->ptr) : nullptr;
        if (QQuick3DDefaultMaterial *mat = buildType(def, ctx, ret, base)) {
            // If this is a component we'll store it for lookups later.
            if (doRegisterComponent)
                registerComponent({ mat, type });

            if (ctx.property.target) {
                if (ctx.property.targetType == TypeInfo<QQuick3DModel>::typeId()) {
                    auto materials = qobject_cast<QQuick3DModel *>(ctx.property.target)->materials();
                    if (ctx.property.memberState == Context::Property::Uninitialized) {
                        if (ctx.dbgprint)
                            printf("Clearing inherited materials\n");
                        materials.clear(&materials);
                        ctx.property.memberState = Context::Property::Initialized;
                    }
                    materials.append(&materials, mat);
                    if (ctx.dbgprint)
                        printf("Appending material to %s\n", ctx.property.name.toLatin1().constData());
                }
            }

            // At this point we don't know if this material is going to be referenced somewhere else, so keep it in the list
            ctx.sceneData.materials.push_back(mat);
        }
    } else if (type == TypeInfo<QQuick3DCustomMaterial>::typeId()) {
        const QQuick3DCustomMaterial *base = (compIt != components.cend()) ? qobject_cast<QQuick3DCustomMaterial *>(compIt->ptr) : nullptr;
        if (QQuick3DCustomMaterial *mat = buildType(def, ctx, ret, base)) {
            // If this is a component we'll store it for lookups later.
            if (doRegisterComponent)
                registerComponent({ mat, type });

            if (ctx.property.target) {
                if (ctx.property.targetType == TypeInfo<QQuick3DModel>::typeId()) {
                    auto materials = qobject_cast<QQuick3DModel *>(ctx.property.target)->materials();
                    if (ctx.property.memberState == Context::Property::Uninitialized) {
                        if (ctx.dbgprint)
                            printf("Clearing inherited materials\n");
                        materials.clear(&materials);
                        ctx.property.memberState = Context::Property::Initialized;
                    }
                    materials.append(&materials, mat);
                    if (ctx.dbgprint)
                        printf("Appending material to %s\n", ctx.property.name.toLatin1().constData());
                }
            }

            // At this point we don't know if this material is going to be referenced somewhere else, so keep it in the list
            ctx.sceneData.materials.push_back(mat);
        }
    } else if (type == TypeInfo<QQuick3DEffect>::typeId()) {
        const QQuick3DEffect *base = (compIt != components.cend()) ? qobject_cast<QQuick3DEffect *>(compIt->ptr) : nullptr;
        if (QQuick3DEffect *effect = buildType(def, ctx, ret, base)) {
            // If this is a component we'll store it for lookups later.
            if (doRegisterComponent)
                registerComponent({ effect, type });

            if (ctx.property.target) {
                if (ctx.property.targetType == TypeInfo<QQuick3DSceneEnvironment>::typeId()) {
                    auto effects = qobject_cast<QQuick3DSceneEnvironment *>(ctx.property.target)->effects();
                    if (ctx.property.memberState == Context::Property::Uninitialized) {
                        if (ctx.dbgprint)
                            printf("Clearing inherited effects\n");
                        effects.clear(&effects);
                        ctx.property.memberState = Context::Property::Initialized;
                    }
                    effects.append(&effects, effect);
                    if (ctx.dbgprint)
                        printf("Appending effect to %s\n", ctx.property.name.toLatin1().constData());
                }
            }

            // At this point we don't know if this effect is going to be referenced somewhere else, so keep it in the list
            ctx.sceneData.effects.push_back(effect);
        }
    } else if (type == TypeInfo<QQuick3DDirectionalLight>::typeId() || type == TypeInfo<QQuick3DPointLight>::typeId() || type == TypeInfo<QQuick3DSpotLight>::typeId())  {
        const QQuick3DAbstractLight *base = (compIt != components.cend()) ? qobject_cast<QQuick3DAbstractLight *>(compIt->ptr) : nullptr;
        if (QQuick3DAbstractLight *light = buildLight(def, ctx, ret, type, base)) {
            // If this is a component we'll store it for lookups later.
            if (doRegisterComponent)
                registerComponent({ light, type });

            ctx.sceneData.lights.push_back(light);
        }
    } else if (type == TypeInfo<QQuick3DTexture>::typeId()) {
        const QQuick3DTexture *base = (compIt != components.cend()) ? qobject_cast<QQuick3DTexture *>(compIt->ptr) : nullptr;
        if (QQuick3DTexture *tex = buildType(def, ctx, ret, base)) {
            // If this is a component we'll store it for lookups later.
            if (doRegisterComponent)
                registerComponent({ tex, type });

            ctx.sceneData.textures.push_back(tex);
        }
    } else if (type == TypeInfo<QQuick3DModel>::typeId()) {
        const auto *base = (compIt != components.cend()) ? qobject_cast<QQuick3DModel *>(compIt->ptr) : nullptr;
        if (auto *model = buildType(def, ctx, ret, base)) {
            // If this is a component we'll store it for lookups later.
            if (doRegisterComponent)
                registerComponent({ model, type });

            ctx.sceneData.models.push_back(model);
        }
    } else if (type == TypeInfo<QQuick3DShaderUtilsShader>::typeId()) {
        const auto *base = (compIt != components.cend()) ? qobject_cast<QQuick3DShaderUtilsShader *>(compIt->ptr) : nullptr;
        if (auto *shader = buildType(def, ctx, ret, base)) {
            // If this is a component we'll store it for lookups later.
            if (doRegisterComponent)
                registerComponent({ shader, type });
            if (ctx.property.target) {
                if (ctx.property.targetType == TypeInfo<QQuick3DShaderUtilsRenderPass>::typeId()) {
                    auto shaders = qobject_cast<QQuick3DShaderUtilsRenderPass *>(ctx.property.target)->shaders();
                    if (ctx.property.memberState == Context::Property::Uninitialized) {
                        if (ctx.dbgprint)
                            printf("Clearing inherited shaders\n");
                        shaders.clear(&shaders);
                        ctx.property.memberState = Context::Property::Initialized;
                    }
                    shaders.append(&shaders, shader);
                    if (ctx.dbgprint)
                        printf("Appending shader to %s\n", ctx.property.name.toLatin1().constData());
                }
            }

            ctx.sceneData.shaders.push_back(shader);
        }
    } else if (type == TypeInfo<QQuick3DShaderUtilsRenderPass>::typeId()) {
        const auto *base = (compIt != components.cend()) ? qobject_cast<QQuick3DShaderUtilsRenderPass *>(compIt->ptr) : nullptr;
        if (auto *pass = buildType(def, ctx, ret, base)) {
            // If this is a component we'll store it for lookups later.
            if (doRegisterComponent)
                registerComponent({ pass, type });
            if (ctx.property.target) {
                if (ctx.property.targetType == TypeInfo<QQuick3DEffect>::typeId()) {
                    auto passes = qobject_cast<QQuick3DEffect *>(ctx.property.target)->passes();
                    if (ctx.property.memberState == Context::Property::Uninitialized) {
                        if (ctx.dbgprint)
                            printf("Clearing inherited passes\n");
                        passes.clear(&passes);
                        ctx.property.memberState = Context::Property::Initialized;
                    }
                    passes.append(&passes, pass);
                    if (ctx.dbgprint)
                        printf("Appending pass to %s\n", ctx.property.name.toLatin1().constData());
                }
            }
        }
    } else if (type == TypeInfo<QQuick3DInstanceList>::typeId()) {
        const auto *base = (compIt != components.cend()) ? qobject_cast<QQuick3DInstanceList *>(compIt->ptr) : nullptr;
        if (auto *instanceList = buildType(def, ctx, ret, base)) {
            // If this is a component we'll store it for lookups later.
            if (doRegisterComponent)
                registerComponent({ instanceList, type });
            if (ctx.property.target) {
                if (ctx.property.targetType == TypeInfo<QQuick3DModel>::typeId()) {
                    qobject_cast<QQuick3DModel *>(ctx.property.target)->setInstancing(instanceList);
                    if (ctx.dbgprint)
                        printf("Setting instance list on %s\n", ctx.property.name.toLatin1().constData());
                }
            }
        }
    } else if (type == TypeInfo<QQuick3DInstanceListEntry>::typeId()) {
        const auto *base = (compIt != components.cend()) ? qobject_cast<QQuick3DInstanceListEntry *>(compIt->ptr) : nullptr;
        if (auto *instanceListEntry = buildType(def, ctx, ret, base)) {
            // If this is a component we'll store it for lookups later.
            if (doRegisterComponent)
                registerComponent({ instanceListEntry, type });
            if (ctx.property.target) {
                if (ctx.property.targetType == TypeInfo<QQuick3DInstanceList>::typeId()) {
                    auto instances = qobject_cast<QQuick3DInstanceList *>(ctx.property.target)->instances();
                    instances.append(&instances, instanceListEntry);
                    if (ctx.dbgprint)
                        printf("Appending instance list entry to %s\n", ctx.property.name.toLatin1().constData());
                }
            }
        }
    } else {
        if (ctx.dbgprint)
            printf("Object def for \'%s\' was not handled\n", ctx.property.name.toLatin1().constData());
        return false;
    }

    return true;
}

static bool interceptPublicMember(const QQmlJS::AST::UiPublicMember &member, Context &ctx, int &ret)
{
    Q_UNUSED(ret);
    using namespace QQmlJS::AST;

    if (ctx.dbgprint)
        printf("Intercepted public member!\n");

    if (member.statement && member.statement->kind == Node::Kind_ExpressionStatement) {
        if ((ctx.property.targetType == TypeInfo<QQuick3DCustomMaterial>::typeId() || ctx.property.targetType == TypeInfo<QQuick3DEffect>::typeId()) && member.memberType) {
            // For custom materials we have properties that are user provided, so we'll
            // need to add these to the objects properties (we add these here to be able
            // to piggyback on the existing type matching code)
            if (member.memberType->name == u"real") {
                ctx.property.type = QMetaType::Double;
            } else if (member.memberType->name == u"bool") {
                ctx.property.type = QMetaType::Bool;
            } else if (member.memberType->name == u"int") {
                ctx.property.type = QMetaType::Int;
            } else if (member.memberType->name == u"size") {
                ctx.property.type = QMetaType::QSizeF;
            } else if (member.memberType->name == u"rect") {
                ctx.property.type = QMetaType::QRectF;
            } else if (member.memberType->name == u"point") {
                ctx.property.type = QMetaType::QPointF;
            } else if (member.memberType->name == u"color") {
                ctx.property.type = QMetaType::QColor;
            } else if (member.memberType->name.startsWith(u"vector")) {
                if (member.memberType->name.endsWith(u"2d")) {
                    ctx.property.type = QMetaType::QVector2D;
                } else if (member.memberType->name.endsWith(u"3d")) {
                    ctx.property.type = QMetaType::QVector3D;
                } else if (member.memberType->name.endsWith(u"4d")) {
                    ctx.property.type = QMetaType::QVector4D;
                }
            } else if (member.memberType->name == u"matrix4x4") {
                ctx.property.type = QMetaType::QMatrix4x4;;
            } else if (member.memberType->name == u"quaternion") {
                ctx.property.type = QMetaType::QQuaternion;
            } else if (member.memberType->name == u"var") {
                ctx.property.type = QMetaType::QVariant;
            }
        }
    }

    return false;
}

static bool interceptCallExpression(const QQmlJS::AST::CallExpression &callExpression, Context &ctx, int &ret)
{
    Q_UNUSED(ret);
    using namespace QQmlJS::AST;
    using namespace BuiltinHelpers;

    if (ctx.dbgprint)
        printf("Intercepted call expression!\n");

    const bool ok = (ctx.property.target && !ctx.property.name.isEmpty());
    if (callExpression.base && ok) {
        if (callExpression.base->kind == Node::Kind_FieldMemberExpression) {
            const auto &fieldMemberExpression = static_cast<const FieldMemberExpression &>(*callExpression.base);
            if (fieldMemberExpression.base) {
                if (fieldMemberExpression.base->kind == Node::Kind_IdentifierExpression) {
                    const auto &identExpr = static_cast<const IdentifierExpression &>(*fieldMemberExpression.base);
                    if (identExpr.name == u"Qt") {
                        bool ok = false;
                        QVariant v;
                        if (fieldMemberExpression.name == u"point") {
                            const auto point = toPoint(ArgumentListView(*callExpression.arguments), &ok);
                            if (ctx.dbgprint)
                                printf("Qt.point(%f, %f)\n", point.x(), point.y());
                            setProperty(ctx.property, point);
                        } else if (fieldMemberExpression.name == u"size") {
                            const auto size = toSize(ArgumentListView(*callExpression.arguments), &ok);
                            if (ctx.dbgprint)
                                printf("Qt.size(%f, %f)\n", size.width(), size.height());
                            setProperty(ctx.property, size);
                        } else if (fieldMemberExpression.name == u"rect") {
                            const auto rect = toRect(ArgumentListView(*callExpression.arguments), &ok);
                            if (ctx.dbgprint)
                                printf("Qt.rect(%f, %f, %f, %f)\n", rect.x(), rect.y(), rect.width(), rect.height());
                            setProperty(ctx.property, rect);
                        } else if (fieldMemberExpression.name.startsWith(u"vector")) {
                            if (fieldMemberExpression.name.endsWith(u"2d")) {
                                const auto vec2 = toVec<QVector2D>(ArgumentListView(*callExpression.arguments), &ok);
                                if (ctx.dbgprint)
                                    printf("Qt.vector2d(%f, %f)\n", vec2.x(), vec2.y());
                                setProperty(ctx.property, vec2);
                            } else if (fieldMemberExpression.name.endsWith(u"3d")) {
                                const auto vec3 = toVec<QVector3D>(ArgumentListView(*callExpression.arguments), &ok);
                                if (ctx.dbgprint)
                                    printf("Qt.vector3d(%f, %f, %f)\n", vec3.x(), vec3.y(), vec3.z());
                                setProperty(ctx.property, vec3);
                            } else if (fieldMemberExpression.name.endsWith(u"4d")) {
                                const auto vec4 = toVec<QVector4D>(ArgumentListView(*callExpression.arguments), &ok);
                                if (ctx.dbgprint)
                                    printf("Qt.vector4d(%f, %f, %f, %f)\n", vec4.x(), vec4.y(), vec4.z(), vec4.w());
                                setProperty(ctx.property, vec4);
                            }
                        } else if (fieldMemberExpression.name == u"matrix4x4") {
                            const auto mat44 = toMat44(ArgumentListView(*callExpression.arguments), &ok);
                            if (ctx.dbgprint)
                                printf("Qt.matrix4x4(%f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f)\n",
                                       mat44(0, 0), mat44(0, 1), mat44(0, 2), mat44(0, 3),
                                       mat44(1, 0), mat44(1, 1), mat44(1, 2), mat44(1, 3),
                                       mat44(2, 0), mat44(2, 1), mat44(2, 2), mat44(2, 3),
                                       mat44(3, 0), mat44(3, 1), mat44(3, 2), mat44(3, 3));
                            setProperty(ctx.property, mat44);
                        } else if (fieldMemberExpression.name == u"quaternion") {
                            const auto quat = toQuaternion(ArgumentListView(*callExpression.arguments), &ok);
                            if (ctx.dbgprint)
                                printf("Qt.quaternion(%f, %f, %f, %f)\n", quat.scalar(), quat.x(), quat.y(), quat.z());
                            setProperty(ctx.property, quat);
                        } else if (fieldMemberExpression.name == u"rgba") {
                            const auto vec4 = toVec<QVector4D>(ArgumentListView(*callExpression.arguments), &ok);
                            if (ok) {
                                QColor color = QColor::fromRgbF(vec4.x(), vec4.y(), vec4.z(), vec4.w());
                                if (ctx.dbgprint)
                                    printf("Qt.rgba(%f, %f, %f, %f)\n", color.redF(), color.greenF(), color.blueF(), color.alphaF());
                                setProperty(ctx.property, color);
                            }
                        }
                        if (ok && v.isValid() && ctx.property.target)
                            ctx.property.target->setProperty(ctx.property.name.toLatin1().constData(), v);
                    }
                }
            }
        }
    }

    return false;
}

static int parseQmlData(const QByteArray &code, Context &ctx)
{
    Q_ASSERT(ctx.engine && ctx.engine->lexer());
    ctx.identifierMap.clear(); // not visible outside the scope of this "code"
    if (ctx.dbgprint)
        printf("Parsing %s\n", qPrintable(ctx.currentFileInfo.filePath()));
    int ret = 0;
    ctx.engine->lexer()->setCode(QString::fromUtf8(code), 1, true);
    QQmlJS::Parser parser(ctx.engine);
    const bool ok = parser.parse();
    if (ok) {
        const auto program = parser.ast();
        if (program)
            Visitors::visit(*program, ctx, ret);
    } else {
        ret = -1;
        qWarning("Parsing failed due to %s in %s:%d%d", qPrintable(parser.errorMessage()), qPrintable(ctx.currentFileInfo.fileName()), parser.errorLineNumber(), parser.errorColumnNumber());
    }

    return ret;
}

int MaterialParser::parseQmlData(const QByteArray &code, const QString &fileName, MaterialParser::SceneData &sceneData)
{
    // set initial type map
    *s_typeMap = baseTypeMap();

    QQmlJS::Engine engine;
    QQmlJS::Lexer lexer(&engine);

    Context ctx;
    ctx.engine = &engine;
    ctx.interceptODFunc = &interceptObjectDef;
    ctx.interceptOBFunc = &interceptObjectBinding;
    ctx.interceptPMFunc = &interceptPublicMember;
    ctx.interceptCallExpr = &interceptCallExpression;
    ctx.currentFileInfo = QFileInfo(fileName);
    ctx.type = Context::Type::Component;

    const int ret = ::parseQmlData(code, ctx);
    sceneData = std::move(ctx.sceneData);

    return ret;
}

int MaterialParser::parseQmlFiles(const QVector<QString> &filePaths, const QDir &sourceDir, SceneData &sceneData, bool verboseOutput)
{
    // set initial type map
    *s_typeMap = baseTypeMap();

    int ret = 0;

    if (filePaths.isEmpty()) {
        qWarning("No input files");
        return ret;
    }

    QQmlJS::Engine engine;
    QQmlJS::Lexer lexer(&engine);

    Context ctx;
    ctx.dbgprint = verboseOutput;
    ctx.engine = &engine;
    ctx.interceptODFunc = &interceptObjectDef;
    ctx.interceptOBFunc = &interceptObjectBinding;
    ctx.interceptPMFunc = &interceptPublicMember;
    ctx.interceptCallExpr = &interceptCallExpression;
    ctx.workingDir = sourceDir;

    QVector<QString> deferredOther;
    QVector<QString> deferredComponets;

    const QString sourcePath = sourceDir.canonicalPath() + QDir::separator();

    const bool isMultifile = filePaths.size() != 1;

    // Go through and find the material components first
    for (const auto &v : filePaths) {
        QFileInfo &currentFileInfo = ctx.currentFileInfo;
        if (!QFileInfo(v).isAbsolute())
            currentFileInfo.setFile(sourcePath + v);
        else
            currentFileInfo.setFile(v);
        const bool maybeComponent = currentFileInfo.fileName().at(0).isUpper();
        if (currentFileInfo.isFile() && currentFileInfo.suffix() == getQmlFileExtension()) {
            const QString filePath = currentFileInfo.canonicalFilePath();
            if (isMultifile && maybeComponent) {
                QFile f(filePath);
                if (!f.open(QFile::ReadOnly)) {
                    qWarning("Could not open file %s for reading!", qPrintable(filePath));
                    return -1;
                }

                const QByteArray code = f.readAll();
                int idx = code.indexOf('{');
                if (idx != -1) {
                    const QByteArray section = code.mid(0, idx);
                    QVarLengthArray<const char *, 3> componentTypes { TypeInfo<QQuick3DPrincipledMaterial>::qmlTypeName(),
                                                                           TypeInfo<QQuick3DCustomMaterial>::qmlTypeName(),
                                                                           TypeInfo<QQuick3DDefaultMaterial>::qmlTypeName()};
                    for (const auto compType : std::as_const(componentTypes)) {
                        if ((idx = section.indexOf(compType)) != -1)
                            break;
                    }
                    if (idx != -1) {
                        ctx.type = Context::Type::Component;
                        ret = parseQmlData(code, ctx);
                        if (ret != 0)
                            break;
                    } else {
                        deferredComponets.push_back(filePath);
                    }
                } else {
                    qWarning("No items found in %s\n", qPrintable(filePath));
                }
            } else {
                deferredOther.push_back(filePath);
            }
        } else {
            qWarning("The file %s is either not a file or has the wrong extension!", qPrintable(v));
        }
    }

    const auto parsePaths = [&ctx, &ret](const QVector<QString> &paths, Context::Type type) {
        ctx.type = type;
        for (const auto &path : paths) {
            QFileInfo &currentFileInfo = ctx.currentFileInfo;
            currentFileInfo.setFile(path);
            if (currentFileInfo.isFile() && currentFileInfo.suffix() == getQmlFileExtension()) {
                const QString filePath = currentFileInfo.canonicalFilePath();
                QFile f(filePath);
                if (!f.open(QFile::ReadOnly)) {
                    qWarning("Could not open file %s for reading!", qPrintable(filePath));
                    ret =  -1;
                    return;
                }

                const QByteArray code = f.readAll();
                ret = parseQmlData(code, ctx);
                if (ret != 0)
                    break;
            }
        }
    };

    // Other components
    parsePaths(deferredComponets, Context::Type::Component);

    // Now parse the rest
    parsePaths(deferredOther, Context::Type::Application);

    sceneData = std::move(ctx.sceneData);

    return ret;
}

QT_END_NAMESPACE