summaryrefslogtreecommitdiffstats
path: root/src/qdoc/qdoc/src/qdoc/config.cpp
blob: c60ef9facf06ff194c993a04c3d651bb3b53fa48 (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
// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "config.h"
#include "utilities.h"

#include <QtCore/qdir.h>
#include <QtCore/qfile.h>
#include <QtCore/qtemporaryfile.h>
#include <QtCore/qtextstream.h>
#include <QtCore/qvariant.h>
#include <QtCore/qregularexpression.h>

QT_BEGIN_NAMESPACE

QString ConfigStrings::AUTOLINKERRORS = QStringLiteral("autolinkerrors");
QString ConfigStrings::BUILDVERSION = QStringLiteral("buildversion");
QString ConfigStrings::CODEINDENT = QStringLiteral("codeindent");
QString ConfigStrings::CODEPREFIX = QStringLiteral("codeprefix");
QString ConfigStrings::CODESUFFIX = QStringLiteral("codesuffix");
QString ConfigStrings::CPPCLASSESPAGE = QStringLiteral("cppclassespage");
QString ConfigStrings::CPPCLASSESTITLE = QStringLiteral("cppclassestitle");
QString ConfigStrings::DEFINES = QStringLiteral("defines");
QString ConfigStrings::DEPENDS = QStringLiteral("depends");
QString ConfigStrings::DESCRIPTION = QStringLiteral("description");
QString ConfigStrings::DOCBOOKEXTENSIONS = QStringLiteral("usedocbookextensions");
QString ConfigStrings::ENDHEADER = QStringLiteral("endheader");
QString ConfigStrings::EXAMPLEDIRS = QStringLiteral("exampledirs");
QString ConfigStrings::EXAMPLES = QStringLiteral("examples");
QString ConfigStrings::EXAMPLESINSTALLPATH = QStringLiteral("examplesinstallpath");
QString ConfigStrings::EXCLUDEDIRS = QStringLiteral("excludedirs");
QString ConfigStrings::EXCLUDEFILES = QStringLiteral("excludefiles");
QString ConfigStrings::EXTRAIMAGES = QStringLiteral("extraimages");
QString ConfigStrings::FALSEHOODS = QStringLiteral("falsehoods");
QString ConfigStrings::FORMATTING = QStringLiteral("formatting");
QString ConfigStrings::HEADERDIRS = QStringLiteral("headerdirs");
QString ConfigStrings::HEADERS = QStringLiteral("headers");
QString ConfigStrings::HEADERSCRIPTS = QStringLiteral("headerscripts");
QString ConfigStrings::HEADERSTYLES = QStringLiteral("headerstyles");
QString ConfigStrings::HOMEPAGE = QStringLiteral("homepage");
QString ConfigStrings::HOMETITLE = QStringLiteral("hometitle");
QString ConfigStrings::IGNOREDIRECTIVES = QStringLiteral("ignoredirectives");
QString ConfigStrings::IGNORESINCE = QStringLiteral("ignoresince");
QString ConfigStrings::IGNORETOKENS = QStringLiteral("ignoretokens");
QString ConfigStrings::IGNOREWORDS = QStringLiteral("ignorewords");
QString ConfigStrings::IMAGEDIRS = QStringLiteral("imagedirs");
QString ConfigStrings::INCLUDEPATHS = QStringLiteral("includepaths");
QString ConfigStrings::INCLUSIVE = QStringLiteral("inclusive");
QString ConfigStrings::INDEXES = QStringLiteral("indexes");
QString ConfigStrings::LANDINGPAGE = QStringLiteral("landingpage");
QString ConfigStrings::LANDINGTITLE = QStringLiteral("landingtitle");
QString ConfigStrings::LANGUAGE = QStringLiteral("language");
QString ConfigStrings::LOCATIONINFO = QStringLiteral("locationinfo");
QString ConfigStrings::LOGPROGRESS = QStringLiteral("logprogress");
QString ConfigStrings::MACRO = QStringLiteral("macro");
QString ConfigStrings::MANIFESTMETA = QStringLiteral("manifestmeta");
QString ConfigStrings::MODULEHEADER = QStringLiteral("moduleheader");
QString ConfigStrings::NATURALLANGUAGE = QStringLiteral("naturallanguage");
QString ConfigStrings::NAVIGATION = QStringLiteral("navigation");
QString ConfigStrings::NOLINKERRORS = QStringLiteral("nolinkerrors");
QString ConfigStrings::OUTPUTDIR = QStringLiteral("outputdir");
QString ConfigStrings::OUTPUTFORMATS = QStringLiteral("outputformats");
QString ConfigStrings::OUTPUTPREFIXES = QStringLiteral("outputprefixes");
QString ConfigStrings::OUTPUTSUFFIXES = QStringLiteral("outputsuffixes");
QString ConfigStrings::PROJECT = QStringLiteral("project");
QString ConfigStrings::REDIRECTDOCUMENTATIONTODEVNULL =
        QStringLiteral("redirectdocumentationtodevnull");
QString ConfigStrings::QHP = QStringLiteral("qhp");
QString ConfigStrings::QUOTINGINFORMATION = QStringLiteral("quotinginformation");
QString ConfigStrings::SCRIPTS = QStringLiteral("scripts");
QString ConfigStrings::SHOWINTERNAL = QStringLiteral("showinternal");
QString ConfigStrings::SINGLEEXEC = QStringLiteral("singleexec");
QString ConfigStrings::SOURCEDIRS = QStringLiteral("sourcedirs");
QString ConfigStrings::SOURCEENCODING = QStringLiteral("sourceencoding");
QString ConfigStrings::SOURCES = QStringLiteral("sources");
QString ConfigStrings::SPURIOUS = QStringLiteral("spurious");
QString ConfigStrings::STYLESHEETS = QStringLiteral("stylesheets");
QString ConfigStrings::SYNTAXHIGHLIGHTING = QStringLiteral("syntaxhighlighting");
QString ConfigStrings::TABSIZE = QStringLiteral("tabsize");
QString ConfigStrings::TAGFILE = QStringLiteral("tagfile");
QString ConfigStrings::TIMESTAMPS = QStringLiteral("timestamps");
QString ConfigStrings::TOCTITLES = QStringLiteral("toctitles");
QString ConfigStrings::URL = QStringLiteral("url");
QString ConfigStrings::VERSION = QStringLiteral("version");
QString ConfigStrings::VERSIONSYM = QStringLiteral("versionsym");
QString ConfigStrings::FILEEXTENSIONS = QStringLiteral("fileextensions");
QString ConfigStrings::IMAGEEXTENSIONS = QStringLiteral("imageextensions");
QString ConfigStrings::QMLTYPESPAGE = QStringLiteral("qmltypespage");
QString ConfigStrings::QMLTYPESTITLE = QStringLiteral("qmltypestitle");
QString ConfigStrings::WARNINGLIMIT = QStringLiteral("warninglimit");

/*!
  An entry in a stack, where each entry is a list
  of string values.
 */
class MetaStackEntry
{
public:
    void open();
    void close();

    QStringList accum;
    QStringList next;
};
Q_DECLARE_TYPEINFO(MetaStackEntry, Q_RELOCATABLE_TYPE);

/*!
  Start accumulating values in a list by appending an empty
  string to the list.
 */
void MetaStackEntry::open()
{
    next.append(QString());
}

/*!
  Stop accumulating values and append the list of accumulated
  values to the complete list of accumulated values.

 */
void MetaStackEntry::close()
{
    accum += next;
    next.clear();
}

/*!
  \class MetaStack

  This class maintains a stack of values of config file variables.
*/
class MetaStack : private QStack<MetaStackEntry>
{
public:
    MetaStack();

    void process(QChar ch, const Location &location);
    QStringList getExpanded(const Location &location);
};

/*!
  The default constructor pushes a new stack entry and
  opens it.
 */
MetaStack::MetaStack()
{
    push(MetaStackEntry());
    top().open();
}

/*!
  Processes the character \a ch using the \a location.
  It really just builds up a name by appending \a ch to
  it.
 */
void MetaStack::process(QChar ch, const Location &location)
{
    if (ch == QLatin1Char('{')) {
        push(MetaStackEntry());
        top().open();
    } else if (ch == QLatin1Char('}')) {
        if (size() == 1)
            location.fatal(QStringLiteral("Unexpected '}'"));

        top().close();
        const QStringList suffixes = pop().accum;
        const QStringList prefixes = top().next;

        top().next.clear();
        for (const auto &prefix : prefixes) {
            for (const auto &suffix : suffixes)
                top().next << prefix + suffix;
        }
    } else if (ch == QLatin1Char(',') && size() > 1) {
        top().close();
        top().open();
    } else {
        for (QString &topNext : top().next)
            topNext += ch;
    }
}

/*!
  Returns the accumulated string values.
 */
QStringList MetaStack::getExpanded(const Location &location)
{
    if (size() > 1)
        location.fatal(QStringLiteral("Missing '}'"));

    top().close();
    return top().accum;
}

const QString Config::dot = QLatin1String(".");
bool Config::m_debug = false;
bool Config::m_atomsDump = false;
bool Config::generateExamples = true;
QString Config::overrideOutputDir;
QString Config::installDir;
QSet<QString> Config::overrideOutputFormats;
QMap<QString, QString> Config::m_extractedDirs;
QStack<QString> Config::m_workingDirs;
QMap<QString, QStringList> Config::m_includeFilesMap;

/*!
  \class ConfigVar
  \brief contains all the information for a single config variable in a
         .qdocconf file.
*/

/*!
  Returns this configuration variable as a string.

  If the variable is not defined, returns \a defaultString.

  \note By default, \a defaultString is a null string.
  This allows determining whether a configuration variable is
  undefined (returns a null string) or defined as empty
  (returns a non-null, empty string).
*/
QString ConfigVar::asString(const QString defaultString) const
{
    if (m_name.isEmpty())
        return defaultString;

    QString result(""); // an empty but non-null string
    for (const auto &value : std::as_const(m_values)) {
        if (!result.isEmpty() && !result.endsWith(QChar('\n')))
            result.append(QChar(' '));
        result.append(value.m_value);
    }
    return result;
}

/*!
  Returns this config variable as a string list.
*/
QStringList ConfigVar::asStringList() const
{
    QStringList result;
    for (const auto &value : std::as_const(m_values))
        result << value.m_value;
    return result;
}

/*!
  Returns this config variable as a string set.
*/
QSet<QString> ConfigVar::asStringSet() const
{
    const auto &stringList = asStringList();
    return QSet<QString>(stringList.cbegin(), stringList.cend());
}

/*!
  Returns this config variable as a boolean.
*/
bool ConfigVar::asBool() const
{
    return QVariant(asString()).toBool();
}

/*!
  Returns this configuration variable as an integer; iterates
  through the string list, interpreting each
  string in the list as an integer and adding it to a total sum.

  Returns 0 if this variable is defined as empty, and
  -1 if it's is not defined.
 */
int ConfigVar::asInt() const
{
    const QStringList strs = asStringList();
    if (strs.isEmpty())
        return -1;

    int sum = 0;
    for (const auto &str : strs)
        sum += str.toInt();
    return sum;
}

/*!
  Appends values to this ConfigVar, and adjusts the ExpandVar
  parameters so that they continue to refer to the correct values.
*/
void ConfigVar::append(const ConfigVar &other)
{
    m_expandVars << other.m_expandVars;
    QList<ExpandVar>::Iterator it = m_expandVars.end();
    it -= other.m_expandVars.size();
    std::for_each(it, m_expandVars.end(), [this](ExpandVar &v) {
        v.m_valueIndex += m_values.size();
    });
    m_values << other.m_values;
    m_location = other.m_location;
}

/*!
  \class Config
  \brief The Config class contains the configuration variables
  for controlling how qdoc produces documentation.

  Its load() function reads, parses, and processes a qdocconf file.
 */

/*!
  \enum Config::PathFlags

  Flags used for retrieving canonicalized paths from Config.

  \value Validate
         Issue a warning for paths that do not exist and
         remove them from the returned list.

  \value IncludePaths
         Assume the variable contains include paths with
         prefixes such as \c{-I} that are to be removed
         before canonicalizing and then re-inserted.

  \omitvalue None

  \sa getCanonicalPathList()
*/

/*!
  Initializes the Config with \a programName and sets all
  internal state variables to either default values or to ones
  defined in command line arguments \a args.
 */
void Config::init(const QString &programName, const QStringList &args)
{
    m_prog = programName;
    processCommandLineOptions(args);
    reset();
}

Config::~Config()
{
    clear();
}

/*!
  Clears the location and internal maps for config variables.
 */
void Config::clear()
{
    m_location = Location();
    m_configVars.clear();
    m_includeFilesMap.clear();
    m_excludedPaths.reset();
}

/*!
  Resets the Config instance - used by load()
 */
void Config::reset()
{
    clear();

    // Default values
    setStringList(CONFIG_CODEINDENT, QStringList("0"));
    setStringList(CONFIG_FALSEHOODS, QStringList("0"));
    setStringList(CONFIG_HEADERS + dot + CONFIG_FILEEXTENSIONS, QStringList("*.ch *.h *.h++ *.hh *.hpp *.hxx"));
    setStringList(CONFIG_SOURCES + dot + CONFIG_FILEEXTENSIONS, QStringList("*.c++ *.cc *.cpp *.cxx *.mm *.qml *.qdoc"));
    setStringList(CONFIG_LANGUAGE, QStringList("Cpp")); // i.e. C++
    setStringList(CONFIG_OUTPUTFORMATS, QStringList("HTML"));
    setStringList(CONFIG_TABSIZE, QStringList("8"));
    setStringList(CONFIG_LOCATIONINFO, QStringList("true"));

    // Publish options from the command line as config variables
    const auto setListFlag = [this](const QString &key, bool test) {
        setStringList(key, QStringList(test ? QStringLiteral("true") : QStringLiteral("false")));
    };
#define SET(opt, test) setListFlag(opt, m_parser.isSet(m_parser.test))
    SET(CONFIG_SYNTAXHIGHLIGHTING, highlightingOption);
    SET(CONFIG_SHOWINTERNAL, showInternalOption);
    SET(CONFIG_SINGLEEXEC, singleExecOption);
    SET(CONFIG_REDIRECTDOCUMENTATIONTODEVNULL, redirectDocumentationToDevNullOption);
    SET(CONFIG_AUTOLINKERRORS, autoLinkErrorsOption);
#undef SET
    m_showInternal = m_configVars.value(CONFIG_SHOWINTERNAL).asBool();
    setListFlag(CONFIG_NOLINKERRORS,
                m_parser.isSet(m_parser.noLinkErrorsOption)
                        || qEnvironmentVariableIsSet("QDOC_NOLINKERRORS"));

    // CONFIG_DEFINES and CONFIG_INCLUDEPATHS are set in load()
}

/*!
  Loads and parses the qdoc configuration file \a fileName.
  If a previous project was loaded, this function first resets the
  Config instance. Then it calls the other load() function, which
  does the loading, parsing, and processing of the configuration file.
 */
void Config::load(const QString &fileName)
{
    // Reset if a previous project was loaded
    if (m_configVars.contains(CONFIG_PROJECT))
        reset();

    load(Location(), fileName);
    if (m_location.isEmpty())
        m_location = Location(fileName);
    else
        m_location.setEtc(true);

    expandVariables();

    // Add defines and includepaths from command line to their
    // respective configuration variables. Values set here are
    // always added to what's defined in configuration file.
    insertStringList(CONFIG_DEFINES, m_defines);
    insertStringList(CONFIG_INCLUDEPATHS, m_includePaths);

    // Prefetch values that are used internally
    m_exampleFiles = getCanonicalPathList(CONFIG_EXAMPLES);
    m_exampleDirs = getCanonicalPathList(CONFIG_EXAMPLEDIRS);
}

/*!
    Expands other config variables referred to in all stored ConfigVars.
*/
void Config::expandVariables()
{
     for (auto &configVar : m_configVars) {
        for (auto it = configVar.m_expandVars.crbegin(); it != configVar.m_expandVars.crend(); ++it) {
            Q_ASSERT(it->m_valueIndex < configVar.m_values.size());
            const QString &key = it->m_var;
            const auto &refVar = m_configVars.value(key);
            if (refVar.m_name.isEmpty()) {
                configVar.m_location.fatal(
                        QStringLiteral("Environment or configuration variable '%1' undefined")
                                .arg(it->m_var));
            } else if (!refVar.m_expandVars.empty()) {
                configVar.m_location.fatal(
                        QStringLiteral("Nested variable expansion not allowed"),
                        QStringLiteral("When expanding '%1' at %2:%3")
                                .arg(refVar.m_name, refVar.m_location.filePath(),
                                     QString::number(refVar.m_location.lineNo())));
            }
            QString expanded;
            if (it->m_delim.isNull())
                expanded = m_configVars.value(key).asStringList().join(QString());
            else
                expanded = m_configVars.value(key).asStringList().join(it->m_delim);
            configVar.m_values[it->m_valueIndex].m_value.insert(it->m_index, expanded);
        }
        configVar.m_expandVars.clear();
     }
}

/*!
  Sets the \a values of a configuration variable \a var from a string list.
 */
void Config::setStringList(const QString &var, const QStringList &values)
{
    m_configVars.insert(var, ConfigVar(var, values, QDir::currentPath()));
}

/*!
  Adds the \a values from a string list to the configuration variable \a var.
  Existing value(s) are kept.
*/
void Config::insertStringList(const QString &var, const QStringList &values)
{
    m_configVars[var].append(ConfigVar(var, values, QDir::currentPath()));
}

/*!
  Process and store variables from the command line.
 */
void Config::processCommandLineOptions(const QStringList &args)
{
    m_parser.process(args);

    m_defines = m_parser.values(m_parser.defineOption);
    m_dependModules = m_parser.values(m_parser.dependsOption);
    setIndexDirs();
    setIncludePaths();

    generateExamples = !m_parser.isSet(m_parser.noExamplesOption);
    if (m_parser.isSet(m_parser.installDirOption))
        installDir = m_parser.value(m_parser.installDirOption);
    if (m_parser.isSet(m_parser.outputDirOption))
        overrideOutputDir = QDir(m_parser.value(m_parser.outputDirOption)).absolutePath();

    const auto outputFormats = m_parser.values(m_parser.outputFormatOption);
    for (const auto &format : outputFormats)
        overrideOutputFormats.insert(format);
    m_debug = m_parser.isSet(m_parser.debugOption) || qEnvironmentVariableIsSet("QDOC_DEBUG");
    m_atomsDump = m_parser.isSet(m_parser.atomsDumpOption);
    m_showInternal = m_parser.isSet(m_parser.showInternalOption)
            || qEnvironmentVariableIsSet("QDOC_SHOW_INTERNAL");

    if (m_parser.isSet(m_parser.prepareOption))
        m_qdocPass = Prepare;
    if (m_parser.isSet(m_parser.generateOption))
        m_qdocPass = Generate;
    if (m_debug || m_parser.isSet(m_parser.logProgressOption))
        setStringList(CONFIG_LOGPROGRESS, QStringList("true"));
    if (m_parser.isSet(m_parser.timestampsOption))
        setStringList(CONFIG_TIMESTAMPS, QStringList("true"));
    if (m_parser.isSet(m_parser.useDocBookExtensions))
        setStringList(CONFIG_DOCBOOKEXTENSIONS, QStringList("true"));
}

void Config::setIncludePaths()
{
    QDir currentDir = QDir::current();
    const auto addIncludePaths = [this, currentDir](const char *flag, const QStringList &paths) {
        for (const auto &path : paths)
            m_includePaths << currentDir.absoluteFilePath(path).insert(0, flag);
    };

    addIncludePaths("-I", m_parser.values(m_parser.includePathOption));
#ifdef QDOC_PASS_ISYSTEM
    addIncludePaths("-isystem", m_parser.values(m_parser.includePathSystemOption));
#endif
    addIncludePaths("-F", m_parser.values(m_parser.frameworkOption));
}

/*!
  Stores paths from -indexdir command line option(s).
 */
void Config::setIndexDirs()
{
    m_indexDirs = m_parser.values(m_parser.indexDirOption);
    auto it = std::remove_if(m_indexDirs.begin(), m_indexDirs.end(),
                             [](const QString &s) { return !QFile::exists(s); });

    std::for_each(it, m_indexDirs.end(), [](const QString &s) {
        qCWarning(lcQdoc) << "Cannot find index directory: " << s;
    });
    m_indexDirs.erase(it, m_indexDirs.end());
}

/*!
  Function to return the correct outputdir for the output \a format.
  If \a format is not specified, defaults to 'HTML'.
  outputdir can be set using the qdocconf or the command-line
  variable -outputdir.
  */
QString Config::getOutputDir(const QString &format) const
{
    QString t;
    if (overrideOutputDir.isNull())
        t = m_configVars.value(CONFIG_OUTPUTDIR).asString();
    else
        t = overrideOutputDir;
    if (m_configVars.value(CONFIG_SINGLEEXEC).asBool()) {
        QString project = m_configVars.value(CONFIG_PROJECT).asString();
        t += QLatin1Char('/') + project.toLower();
    }
    if (m_configVars.value(format + Config::dot + "nosubdirs").asBool()) {
        QString singleOutputSubdir = m_configVars.value(format + Config::dot + "outputsubdir").asString();
        if (singleOutputSubdir.isEmpty())
            singleOutputSubdir = "html";
        t += QLatin1Char('/') + singleOutputSubdir;
    }
    return QDir::cleanPath(t);
}

/*!
  Function to return the correct outputformats.
  outputformats can be set using the qdocconf or the command-line
  variable -outputformat.
  */
QSet<QString> Config::getOutputFormats() const
{
    if (overrideOutputFormats.isEmpty())
        return m_configVars.value(CONFIG_OUTPUTFORMATS).asStringSet();
    else
        return overrideOutputFormats;
}

// TODO: [late-canonicalization][pod-configuration]
// The canonicalization for paths is done at the time where they are
// required, and done each time they are requested.
// Instead, config should be parsed to an intermediate format that is
// a POD type that already contains canonicalized representations for
// each element.
// Those representations should provide specific guarantees about
// their format and be representable at the API boundaries.
//
// This would ensure that the correct canonicalization is always
// applied, is applied only once and that dependent sub-logics can be
// written in a way that doesn't require branching or futher
// canonicalization.

/*!
   Returns a path list where all paths from the config variable \a var
   are canonicalized. If \a flags contains \c Validate, outputs a warning
   for invalid paths. The \c IncludePaths flag is used as a hint to strip
   away potential prefixes found in include paths before attempting to
   canonicalize.
 */
QStringList Config::getCanonicalPathList(const QString &var, PathFlags flags) const
{
    QStringList result;
    const auto &configVar = m_configVars.value(var);

    for (const auto &value : configVar.m_values) {
        const QString &currentPath = value.m_path;
        QString rawValue = value.m_value.simplified();
        QString prefix;

        if (flags & IncludePaths) {
            const QStringList prefixes = QStringList()
                    << QLatin1String("-I")
                    << QLatin1String("-F")
                    << QLatin1String("-isystem");
            const auto end = std::end(prefixes);
            const auto it =
                std::find_if(std::begin(prefixes), end,
                     [&rawValue](const QString &p) {
                        return rawValue.startsWith(p);
                });
            if (it != end) {
                prefix = *it;
                rawValue.remove(0, it->size());
                if (rawValue.isEmpty())
                    continue;
            } else {
                prefix = prefixes[0]; // -I as default
            }
        }

        QDir dir(rawValue.trimmed());
        const QString path = dir.path();

        if (dir.isRelative())
            dir.setPath(currentPath + QLatin1Char('/') + path);
        if ((flags & Validate) && !QFileInfo::exists(dir.path()))
            configVar.m_location.warning(QStringLiteral("Cannot find file or directory: %1").arg(path));
        else {
            const QString canonicalPath = dir.canonicalPath();
            if (!canonicalPath.isEmpty())
                result.append(prefix + canonicalPath);
            else if (path.contains(QLatin1Char('*')) || path.contains(QLatin1Char('?')))
                result.append(path);
            else
                qCDebug(lcQdoc) <<
                        qUtf8Printable(QStringLiteral("%1: Ignored nonexistent path \'%2\'")
                                .arg(configVar.m_location.toString(), rawValue));
        }
    }
    return result;
}

/*!
  Calls getRegExpList() with the control variable \a var and
  iterates through the resulting list of regular expressions,
  concatenating them with extra characters to form a single
  QRegularExpression, which is then returned.

  \sa getRegExpList()
 */
QRegularExpression Config::getRegExp(const QString &var) const
{
    QString pattern;
    const auto subRegExps = getRegExpList(var);

    for (const auto &regExp : subRegExps) {
        if (!regExp.isValid())
            return regExp;
        if (!pattern.isEmpty())
            pattern += QLatin1Char('|');
        pattern += QLatin1String("(?:") + regExp.pattern() + QLatin1Char(')');
    }
    if (pattern.isEmpty())
        pattern = QLatin1String("$x"); // cannot match
    return QRegularExpression(pattern);
}

/*!
  Looks up the configuration variable \a var in the string list
  map, converts the string list to a list of regular expressions,
  and returns it.
 */
QList<QRegularExpression> Config::getRegExpList(const QString &var) const
{
    const QStringList strs = m_configVars.value(var).asStringList();
    QList<QRegularExpression> regExps;
    for (const auto &str : strs)
        regExps += QRegularExpression(str);
    return regExps;
}

/*!
  This function is slower than it could be. What it does is
  find all the keys that begin with \a var + dot and return
  the matching keys in a set, stripped of the matching prefix
  and dot.
 */
QSet<QString> Config::subVars(const QString &var) const
{
    QSet<QString> result;
    QString varDot = var + QLatin1Char('.');
    for (auto it = m_configVars.constBegin(); it != m_configVars.constEnd(); ++it) {
        if (it.key().startsWith(varDot)) {
            QString subVar = it.key().mid(varDot.size());
            int dot = subVar.indexOf(QLatin1Char('.'));
            if (dot != -1)
                subVar.truncate(dot);
            result.insert(subVar);
        }
    }
    return result;
}

/*!
  Searches for a path to \a fileName in 'sources', 'sourcedirs', and
  'exampledirs' config variables and returns a full path to the first
  match found. If the file is not found, returns an empty string.
 */
QString Config::getIncludeFilePath(const QString &fileName) const
{
    QString ext = QFileInfo(fileName).suffix();

    if (!m_includeFilesMap.contains(ext)) {
        QStringList result = getCanonicalPathList(CONFIG_SOURCES);
        result.erase(std::remove_if(result.begin(), result.end(),
                     [&](const QString &s) { return !s.endsWith(ext); }),
                    result.end());
        const QStringList dirs =
            getCanonicalPathList(CONFIG_SOURCEDIRS) +
            getCanonicalPathList(CONFIG_EXAMPLEDIRS);

        for (const auto &dir : dirs)
            result += getFilesHere(dir, "*." + ext, location());
        result.removeDuplicates();
        m_includeFilesMap.insert(ext, result);
    }
    const QStringList &paths = (*m_includeFilesMap.find(ext));
    QString match = fileName;
    if (!match.startsWith('/'))
        match.prepend('/');
    for (const auto &path : paths) {
        if (path.endsWith(match))
            return path;
    }
    return QString();
}

/*!
  Builds and returns a list of file pathnames for the file
  type specified by \a filesVar (e.g. "headers" or "sources").
  The files are found in the directories specified by
  \a dirsVar, and they are filtered by \a defaultNameFilter
  if a better filter can't be constructed from \a filesVar.
  The directories in \a excludedDirs are avoided. The files
  in \a excludedFiles are not included in the return list.
 */
QStringList Config::getAllFiles(const QString &filesVar, const QString &dirsVar,
                                const QSet<QString> &excludedDirs,
                                const QSet<QString> &excludedFiles)
{
    QStringList result = getCanonicalPathList(filesVar, Validate);
    const QStringList dirs = getCanonicalPathList(dirsVar, Validate);

    const QString nameFilter = m_configVars.value(filesVar + dot + CONFIG_FILEEXTENSIONS).asString();

    for (const auto &dir : dirs)
        result += getFilesHere(dir, nameFilter, location(), excludedDirs, excludedFiles);
    return result;
}

QStringList Config::getExampleQdocFiles(const QSet<QString> &excludedDirs,
                                        const QSet<QString> &excludedFiles)
{
    QStringList result;
    const QStringList dirs = getCanonicalPathList("exampledirs");
    const QString nameFilter = " *.qdoc";

    for (const auto &dir : dirs)
        result += getFilesHere(dir, nameFilter, location(), excludedDirs, excludedFiles);
    return result;
}

QStringList Config::getExampleImageFiles(const QSet<QString> &excludedDirs,
                                         const QSet<QString> &excludedFiles)
{
    QStringList result;
    const QStringList dirs = getCanonicalPathList("exampledirs");
    const QString nameFilter = m_configVars.value(CONFIG_EXAMPLES + dot + CONFIG_IMAGEEXTENSIONS).asString();

    for (const auto &dir : dirs)
        result += getFilesHere(dir, nameFilter, location(), excludedDirs, excludedFiles);
    return result;
}

// TODO: [misplaced-logic][examples][pod-configuration]
// The definition of how an example is structured and how to find its
// components should not be part of Config or, for that matter,
// CppCodeParser, which is the actual caller of this method.
// Move this method to a more appropriate place as soon as a suitable
// place is available for it.

/*!
    Returns the path to the project file for \a examplePath, or an empty string
    if no project file was found.
 */
QString Config::getExampleProjectFile(const QString &examplePath)
{
    QFileInfo fileInfo(examplePath);
    QStringList validNames;
    validNames << QLatin1String("CMakeLists.txt")
               << fileInfo.fileName() + QLatin1String(".pro")
               << fileInfo.fileName() + QLatin1String(".qmlproject")
               << fileInfo.fileName() + QLatin1String(".pyproject")
               << QLatin1String("qbuild.pro"); // legacy

    QString projectFile;

    for (const auto &name : std::as_const(validNames)) {
        projectFile = Config::findFile(Location(), m_exampleFiles, m_exampleDirs,
                                       examplePath + QLatin1Char('/') + name);
        if (!projectFile.isEmpty())
            return projectFile;
    }

    return projectFile;
}

// TODO: [pod-configuration]
// Remove findFile completely from the configuration.
// External usages of findFile were already removed but a last caller
// of this method exists internally to Config in
// `getExampleProjectFile`.
// That method has to be removed at some point and this method should
// go with it.
// Do notice that FileResolver is the replacement for findFile but it
// is designed, for now, with a scope that does only care about the
// usages of findFile that are outside the Config class.
// More specifically, it was designed to replace only the uses of
// findFile that deal with user provided queries or queries related to
// that.
// The logic that is used internally in Config is the same, but has a
// different conceptual meaning.
// When findFile is permanently removed, it must be considered whether
// FileResolver itself should be used for the same logic or not.

/*!
  \a fileName is the path of the file to find.

  \a files and \a dirs are the lists where we must find the
  components of \a fileName.

  \a location is used for obtaining the file and line numbers
  for report qdoc errors.
 */
QString Config::findFile(const Location &location, const QStringList &files,
                         const QStringList &dirs, const QString &fileName,
                         QString *userFriendlyFilePath)
{
    if (fileName.isEmpty() || fileName.startsWith(QLatin1Char('/'))) {
        if (userFriendlyFilePath)
            *userFriendlyFilePath = fileName;
        return fileName;
    }

    QFileInfo fileInfo;
    QStringList components = fileName.split(QLatin1Char('?'));
    QString firstComponent = components.first();

    for (const auto &file : files) {
        if (file == firstComponent || file.endsWith(QLatin1Char('/') + firstComponent)) {
            fileInfo.setFile(file);
            if (!fileInfo.exists())
                location.fatal(QStringLiteral("File '%1' does not exist").arg(file));
            break;
        }
    }

    if (fileInfo.fileName().isEmpty()) {
        for (const auto &dir : dirs) {
            fileInfo.setFile(QDir(dir), firstComponent);
            if (fileInfo.exists())
                break;
        }
    }

    if (userFriendlyFilePath)
        userFriendlyFilePath->clear();
    if (!fileInfo.exists())
        return QString();

    // <<REMARK: This is actually dead code. It is unclear what it tries
    // to do and why but its usage is unnecessary in the current
    // codebase.
    // Indeed, the whole concept of the "userFriendlyFilePath" is
    // removed for file searching.
    // It will be removed directly with the whole of findFile, but it
    // should not be considered anymore until then.
    if (userFriendlyFilePath) {
        for (auto c = components.constBegin();;) {
            bool isArchive = (c != components.constEnd() - 1);
            userFriendlyFilePath->append(*c);

            if (isArchive) {
                QString extracted = m_extractedDirs[fileInfo.filePath()];

                ++c;
                fileInfo.setFile(QDir(extracted), *c);
            } else {
                break;
            }

            userFriendlyFilePath->append(QLatin1Char('?'));
        }
    }
    // REMARK>>

    return fileInfo.filePath();
}

// TODO: [pod-configuration]
// An intermediate representation for the configuration should only
// contain data that will later be destructured into subsystem that
// care about specific subsets of the configuration and can carry that
// information with them, uniquely.
// Remove copyFile, moving it into whatever will have the unique
// resposability of knowing how to build an output directory for a
// QDoc execution.
// Should copy file being used for not only copying file to the build
// output directory, split its responsabilities into smaller elements
// instead of forcing the logic together.

/*!
  Copies the \a sourceFilePath to the file name constructed by
  concatenating \a targetDirPath and the file name from the
  \a userFriendlySourceFilePath. \a location is for identifying
  the file and line number where a qdoc error occurred. The
  constructed output file name is returned.
 */
QString Config::copyFile(const Location &location, const QString &sourceFilePath,
                         const QString &userFriendlySourceFilePath, const QString &targetDirPath)
{
    // TODO: A copying operation should only be performed on files
    // that we assume to be available. Ensure that this is true at the
    // API boundary and bubble up the error checking and reporting to
    // call-site users. Possibly this will be as simple as
    // ResolvedFile, but could not be done at the time of the introduction of
    // that type as we first need to encapsulate the logic for
    // copying files into an appropriate subsystem and have a better
    // understanding of call-site usages.

    QFile inFile(sourceFilePath);
    if (!inFile.open(QFile::ReadOnly)) {
        location.warning(QStringLiteral("Cannot open input file for copy: '%1': %2")
                                 .arg(sourceFilePath, inFile.errorString()));
        return QString();
    }

    // TODO: [non-canonical-representation]
    // Similar to other part of QDoc, we do a series of non-intuitive
    // checks to canonicalize some multi-format parameter into
    // something we can use.
    // Understand which of those formats are actually in use and
    // provide a canonicalized version that can be requested at the
    // API boundary to ensure that correct formatting is used.
    // If possible, gradually bubble up the canonicalization until a
    // single entry-point in the program exists where the
    // canonicalization can be processed to avoid complicating
    // intermediate steps.
    // ADDENDUM 1: At least one usage of this seems to depend on the
    // processing done for files coming from
    // Generator::copyTemplateFile, which are expressed as absolute
    // paths. This seems to be the only usage that is currently
    // needed, hence a temporary new implementation is provided that
    // only takes this case into account.
    // Do notice that we assume that in this case we always want a
    // flat structure, that is, we are copying the file as a direct
    // child of the target directory.
    // Nonetheless, it is possible that this case will not be needed,
    // such that it can be removed later on, or that it will be nedeed
    // in multiple places such that an higher level interface for it
    // should be provided.
    // Furthermoe, it might be possible that there is an edge case
    // that is now not considered, as it is unknown, that was
    // considered before.
    // As it is now unclear what kind of paths are used here, what
    // format they have, why they are used and why they have some
    // specific format, further processing is avoided but a more
    // torough overview of what should is needed must be done when
    // more information are gathered and this function is extracted
    // away from config.

    QString outFileName{userFriendlySourceFilePath};
    QFileInfo outFileNameInfo{userFriendlySourceFilePath};
    if (outFileNameInfo.isAbsolute())
        outFileName = outFileNameInfo.fileName();

    outFileName = targetDirPath + "/" + outFileName;
    QDir targetDir(targetDirPath);
    if (!targetDir.exists())
        targetDir.mkpath(".");

    QFile outFile(outFileName);
    if (!outFile.open(QFile::WriteOnly)) {
        // TODO: [uncrentralized-warning]
        location.warning(QStringLiteral("Cannot open output file for copy: '%1': %2")
                                 .arg(outFileName, outFile.errorString()));
        return QString();
    }

    // TODO: There shouldn't be any particular advantage to copying
    // the file by readying its content and writing it compared to
    // asking the underlying system to do the copy for us.
    // Consider simplifying this part by avoiding doing the manual
    // work ourselves.

    char buffer[1024];
    qsizetype len;
    while ((len = inFile.read(buffer, sizeof(buffer))) > 0)
        outFile.write(buffer, len);
    return outFileName;
}

/*!
  Finds the largest unicode digit in \a value in the range
  1..7 and returns it.
 */
int Config::numParams(const QString &value)
{
    int max = 0;
    for (int i = 0; i != value.size(); ++i) {
        uint c = value[i].unicode();
        if (c > 0 && c < 8)
            max = qMax(max, static_cast<int>(c));
    }
    return max;
}

/*!
  Returns \c true if \a ch is a letter, number, '_', '.',
  '{', '}', or ','.
 */
bool Config::isMetaKeyChar(QChar ch)
{
    return ch.isLetterOrNumber() || ch == QLatin1Char('_') || ch == QLatin1Char('.')
            || ch == QLatin1Char('{') || ch == QLatin1Char('}') || ch == QLatin1Char(',');
}

/*!
  \a fileName is a master qdocconf file. It contains a list of
  qdocconf files and nothing else. Read the list and return it.
 */
QStringList Config::loadMaster(const QString &fileName)
{
    Location location;
    QFile fin(fileName);
    if (!fin.open(QFile::ReadOnly | QFile::Text)) {
        if (!Config::installDir.isEmpty()) {
            qsizetype prefix = location.filePath().size() - location.fileName().size();
            fin.setFileName(Config::installDir + QLatin1Char('/')
                            + fileName.right(fileName.size() - prefix));
        }
        if (!fin.open(QFile::ReadOnly | QFile::Text))
            location.fatal(QStringLiteral("Cannot open master qdocconf file '%1': %2")
                                   .arg(fileName, fin.errorString()));
    }
    QTextStream stream(&fin);
    QStringList qdocFiles;
    QDir configDir(QFileInfo(fileName).canonicalPath());
    QString line = stream.readLine();
    while (!line.isNull()) {
        if (!line.isEmpty())
            qdocFiles.append(QFileInfo(configDir, line).filePath());
        line = stream.readLine();
    }
    fin.close();
    return qdocFiles;
}

/*!
  Load, parse, and process a qdoc configuration file. This
  function is only called by the other load() function, but
  this one is recursive, i.e., it calls itself when it sees
  an \c{include} statement in the qdoc configuration file.
 */
void Config::load(Location location, const QString &fileName)
{
    QFileInfo fileInfo(fileName);
    pushWorkingDir(fileInfo.canonicalPath());
    static const QRegularExpression keySyntax(QRegularExpression::anchoredPattern(QLatin1String("\\w+(?:\\.\\w+)*")));

#define SKIP_CHAR()                                                                                \
    do {                                                                                           \
        location.advance(c);                                                                       \
        ++i;                                                                                       \
        c = text.at(i);                                                                            \
        cc = c.unicode();                                                                          \
    } while (0)

#define SKIP_SPACES()                                                                              \
    while (c.isSpace() && cc != '\n')                                                              \
    SKIP_CHAR()

#define PUT_CHAR()                                                                                 \
    word += c;                                                                                     \
    SKIP_CHAR();

    if (location.depth() > 16)
        location.fatal(QStringLiteral("Too many nested includes"));

    QFile fin(fileInfo.fileName());
    if (!fin.open(QFile::ReadOnly | QFile::Text)) {
        if (!Config::installDir.isEmpty()) {
            qsizetype prefix = location.filePath().size() - location.fileName().size();
            fin.setFileName(Config::installDir + QLatin1Char('/')
                            + fileName.right(fileName.size() - prefix));
        }
        if (!fin.open(QFile::ReadOnly | QFile::Text))
            location.fatal(
                    QStringLiteral("Cannot open file '%1': %2").arg(fileName, fin.errorString()));
    }

    QTextStream stream(&fin);
    QString text = stream.readAll();
    text += QLatin1String("\n\n");
    text += QLatin1Char('\0');
    fin.close();

    location.push(fileName);
    location.start();

    int i = 0;
    QChar c = text.at(0);
    uint cc = c.unicode();
    while (i < text.size()) {
        if (cc == 0) {
            ++i;
        } else if (c.isSpace()) {
            SKIP_CHAR();
        } else if (cc == '#') {
            do {
                SKIP_CHAR();
            } while (cc != '\n');
        } else if (isMetaKeyChar(c)) {
            Location keyLoc = location;
            bool plus = false;
            QStringList rhsValues;
            QList<ExpandVar> expandVars;
            QString word;
            bool inQuote = false;
            bool needsExpansion = false;

            MetaStack stack;
            do {
                stack.process(c, location);
                SKIP_CHAR();
            } while (isMetaKeyChar(c));

            const QStringList keys = stack.getExpanded(location);
            SKIP_SPACES();

            if (keys.size() == 1 && keys.first() == QLatin1String("include")) {
                QString includeFile;

                if (cc != '(')
                    location.fatal(QStringLiteral("Bad include syntax"));
                SKIP_CHAR();
                SKIP_SPACES();

                while (!c.isSpace() && cc != '#' && cc != ')') {

                    if (cc == '$') {
                        QString var;
                        SKIP_CHAR();
                        while (c.isLetterOrNumber() || cc == '_') {
                            var += c;
                            SKIP_CHAR();
                        }
                        if (!var.isEmpty()) {
                            const QByteArray val = qgetenv(var.toLatin1().data());
                            if (val.isNull()) {
                                location.fatal(QStringLiteral("Environment variable '%1' undefined")
                                                       .arg(var));
                            } else {
                                includeFile += QString::fromLatin1(val);
                            }
                        }
                    } else {
                        includeFile += c;
                        SKIP_CHAR();
                    }
                }
                SKIP_SPACES();
                if (cc != ')')
                    location.fatal(QStringLiteral("Bad include syntax"));
                SKIP_CHAR();
                SKIP_SPACES();
                if (cc != '#' && cc != '\n')
                    location.fatal(QStringLiteral("Trailing garbage"));

                /*
                  Here is the recursive call.
                 */
                load(location, QFileInfo(QDir(m_workingDirs.top()), includeFile).filePath());
            } else {
                /*
                  It wasn't an include statement, so it's something else.
                  We must see either '=' or '+=' next. If not, fatal error.
                 */
                if (cc == '+') {
                    plus = true;
                    SKIP_CHAR();
                }
                if (cc != '=')
                    location.fatal(QStringLiteral("Expected '=' or '+=' after key"));
                SKIP_CHAR();
                SKIP_SPACES();

                for (;;) {
                    if (cc == '\\') {
                        qsizetype metaCharPos;

                        SKIP_CHAR();
                        if (cc == '\n') {
                            SKIP_CHAR();
                        } else if (cc > '0' && cc < '8') {
                            word += QChar(c.digitValue());
                            SKIP_CHAR();
                        } else if ((metaCharPos = QString::fromLatin1("abfnrtv").indexOf(c))
                                   != -1) {
                            word += QLatin1Char("\a\b\f\n\r\t\v"[metaCharPos]);
                            SKIP_CHAR();
                        } else {
                            PUT_CHAR();
                        }
                    } else if (c.isSpace() || cc == '#') {
                        if (inQuote) {
                            if (cc == '\n')
                                location.fatal(QStringLiteral("Unterminated string"));
                            PUT_CHAR();
                        } else {
                            if (!word.isEmpty() || needsExpansion) {
                                rhsValues << word;
                                word.clear();
                                needsExpansion = false;
                            }
                            if (cc == '\n' || cc == '#')
                                break;
                            SKIP_SPACES();
                        }
                    } else if (cc == '"') {
                        if (inQuote) {
                            if (!word.isEmpty() || needsExpansion)
                                rhsValues << word;
                            word.clear();
                            needsExpansion = false;
                        }
                        inQuote = !inQuote;
                        SKIP_CHAR();
                    } else if (cc == '$') {
                        QString var;
                        QChar delim(' ');
                        bool braces = false;
                        SKIP_CHAR();
                        if (cc == '{') {
                            SKIP_CHAR();
                            braces = true;
                        }
                        while (c.isLetterOrNumber() || cc == '_') {
                            var += c;
                            SKIP_CHAR();
                        }
                        if (braces) {
                            if (cc == ',') {
                                SKIP_CHAR();
                                delim = c;
                                SKIP_CHAR();
                            }
                            if (cc == '}')
                                SKIP_CHAR();
                            else if (delim == '}')
                                delim = QChar(); // null delimiter
                            else
                                location.fatal(QStringLiteral("Missing '}'"));
                        }
                        if (!var.isEmpty()) {
                            const QByteArray val = qgetenv(var.toLatin1().constData());
                            if (val.isNull()) {
                                expandVars << ExpandVar(rhsValues.size(), word.size(), var, delim);
                                needsExpansion = true;
                            } else if (braces) { // ${VAR} inserts content from an env. variable for processing
                                text.insert(i, QString::fromLatin1(val));
                                c = text.at(i);
                                cc = c.unicode();
                            } else { // while $VAR simply reads the value and stores it to a config variable.
                                word += QString::fromLatin1(val);
                            }
                        }
                    } else {
                        if (!inQuote && cc == '=')
                            location.fatal(QStringLiteral("Unexpected '='"));
                        PUT_CHAR();
                    }
                }
                for (const auto &key : keys) {
                    if (!keySyntax.match(key).hasMatch())
                        keyLoc.fatal(QStringLiteral("Invalid key '%1'").arg(key));

                    ConfigVar configVar(key, rhsValues, QDir::currentPath(), keyLoc, expandVars);
                    if (plus && m_configVars.contains(key)) {
                        m_configVars[key].append(configVar);
                    } else {
                        m_configVars.insert(key, configVar);
                    }
                }
            }
        } else {
            location.fatal(QStringLiteral("Unexpected character '%1' at beginning of line").arg(c));
        }
    }
    popWorkingDir();

#undef SKIP_CHAR
#undef SKIP_SPACES
#undef PUT_CHAR
}

bool Config::isFileExcluded(const QString &fileName, const QSet<QString> &excludedFiles)
{
    for (const QString &entry : excludedFiles) {
        if (entry.contains(QLatin1Char('*')) || entry.contains(QLatin1Char('?'))) {
            QRegularExpression re(QRegularExpression::wildcardToRegularExpression(entry));
            if (re.match(fileName).hasMatch())
                return true;
        }
    }
    return excludedFiles.contains(fileName);
}

QStringList Config::getFilesHere(const QString &uncleanDir, const QString &nameFilter,
                                 const Location &location, const QSet<QString> &excludedDirs,
                                 const QSet<QString> &excludedFiles)
{
    // TODO: Understand why location is used to branch the
    // canonicalization and why the two different methods are used.
    QString dir =
            location.isEmpty() ? QDir::cleanPath(uncleanDir) : QDir(uncleanDir).canonicalPath();
    QStringList result;
    if (excludedDirs.contains(dir))
        return result;

    QDir dirInfo(dir);

    dirInfo.setNameFilters(nameFilter.split(QLatin1Char(' ')));
    dirInfo.setSorting(QDir::Name);
    dirInfo.setFilter(QDir::Files);
    QStringList fileNames = dirInfo.entryList();
    for (const auto &file : std::as_const(fileNames)) {
        // TODO: Understand if this is needed and, should it be, if it
        // is indeed the only case that should be considered.
        if (!file.startsWith(QLatin1Char('~'))) {
            QString s = dirInfo.filePath(file);
            QString c = QDir::cleanPath(s);
            if (!isFileExcluded(c, excludedFiles))
                result.append(c);
        }
    }

    dirInfo.setNameFilters(QStringList(QLatin1String("*")));
    dirInfo.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
    fileNames = dirInfo.entryList();
    for (const auto &file : fileNames)
        result += getFilesHere(dirInfo.filePath(file), nameFilter, location, excludedDirs,
                               excludedFiles);
    return result;
}

/*!
  Set \a dir as the working directory and push it onto the
  stack of working directories.
 */
void Config::pushWorkingDir(const QString &dir)
{
    m_workingDirs.push(dir);
    QDir::setCurrent(dir);
}

/*!
  Pop the top entry from the stack of working directories.
  Set the working directory to the next one on the stack,
  if one exists.
 */
void Config::popWorkingDir()
{
    Q_ASSERT(!m_workingDirs.isEmpty());
    m_workingDirs.pop();
    if (!m_workingDirs.isEmpty())
        QDir::setCurrent(m_workingDirs.top());
}

const Config::ExcludedPaths& Config::getExcludedPaths() {
    if (m_excludedPaths)
        return *m_excludedPaths;

    const auto &excludedDirList = getCanonicalPathList(CONFIG_EXCLUDEDIRS);
    const auto &excludedFilesList = getCanonicalPathList(CONFIG_EXCLUDEFILES);

    QSet<QString> excludedDirs = QSet<QString>(excludedDirList.cbegin(), excludedDirList.cend());
    QSet<QString> excludedFiles = QSet<QString>(excludedFilesList.cbegin(), excludedFilesList.cend());

    m_excludedPaths.emplace(ExcludedPaths{excludedDirs, excludedFiles});

    return *m_excludedPaths;
}

std::set<Config::HeaderFilePath> Config::getHeaderFiles() {
    static QStringList accepted_header_file_extensions{
        "ch", "h", "h++", "hh", "hpp", "hxx"
    };

    const auto& [excludedDirs, excludedFiles] = getExcludedPaths();

    QStringList headerList =
            getAllFiles(CONFIG_HEADERS, CONFIG_HEADERDIRS, excludedDirs, excludedFiles);

    std::set<HeaderFilePath> headers{};

    for (const auto& header : headerList) {
        if (header.contains("doc/snippets")) continue;

        if (!accepted_header_file_extensions.contains(QFileInfo{header}.suffix()))
            continue;

        headers.insert(HeaderFilePath{QFileInfo{header}.canonicalPath(), QFileInfo{header}.fileName()});
    }

    return headers;
}

QT_END_NAMESPACE