File: DeclarationManager.cpp

package info (click to toggle)
darkradiant 3.9.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 41,080 kB
  • sloc: cpp: 264,743; ansic: 10,659; python: 1,852; xml: 1,650; sh: 92; makefile: 21
file content (1016 lines) | stat: -rw-r--r-- 31,260 bytes parent folder | download | duplicates (3)
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
#include <future>
#include <fstream>

#include "i18n.h"
#include "DeclarationManager.h"

#include <regex>

#include "DeclarationFolderParser.h"
#include "parser/DefBlockSyntaxParser.h"
#include "ifilesystem.h"
#include "module/StaticModule.h"
#include "string/trim.h"
#include "os/path.h"
#include "os/file.h"
#include "fmt/format.h"
#include "gamelib.h"
#include "stream/TemporaryOutputStream.h"
#include "util/ScopedBoolLock.h"

namespace decl
{

void DeclarationManager::registerDeclType(const std::string& typeName, const IDeclarationCreator::Ptr& creator)
{
    {
        std::lock_guard creatorLock(_declarationAndCreatorLock);

        if (_creatorsByTypename.count(typeName) > 0 || _creatorsByType.count(creator->getDeclType()) > 0)
        {
            throw std::logic_error("Type name " + typeName + " and/or type " +
                getTypeName(creator->getDeclType()) + " has already been registered");
        }

        _creatorsByTypename.emplace(typeName, creator);
        _creatorsByType.emplace(creator->getDeclType(), creator);
    }

    // A new parser might be able to parse some of the unrecognised blocks
    handleUnrecognisedBlocks();
}

void DeclarationManager::unregisterDeclType(const std::string& typeName)
{
    std::lock_guard parserLock(_declarationAndCreatorLock);

    auto existing = _creatorsByTypename.find(typeName);

    if (existing == _creatorsByTypename.end())
    {
        throw std::logic_error("Type name " + typeName + " has not been registered");
    }

    _creatorsByTypename.erase(existing);
}

void DeclarationManager::registerDeclFolder(Type defaultType, const std::string& inputFolder, const std::string& inputExtension)
{
    // Sanitise input strings
    auto vfsPath = os::standardPathWithSlash(inputFolder);
    auto extension = string::trim_left_copy(inputExtension, ".");

    {
        std::lock_guard folderLock(_registeredFoldersLock);
        _registeredFolders.emplace_back(RegisteredFolder{ vfsPath, extension, defaultType });
    }

    std::lock_guard declLock(_declarationAndCreatorLock);
    auto& decls = _declarationsByType.try_emplace(defaultType, Declarations()).first->second;

    // Start the parser thread
    decls.parser = std::make_unique<DeclarationFolderParser>(*this, defaultType, vfsPath, extension, getTypenameMapping());
    decls.parser->start();
}

std::map<std::string, Type, string::ILess> DeclarationManager::getTypenameMapping()
{
    std::map<std::string, Type, string::ILess> result;

    std::lock_guard creatorLock(_declarationAndCreatorLock);

    for (const auto& [name, creator] : _creatorsByTypename)
    {
        result[name] = creator->getDeclType();
    }

    return result;
}

IDeclaration::Ptr DeclarationManager::findDeclaration(Type type, const std::string& name)
{
    IDeclaration::Ptr returnValue;

    doWithDeclarationLock(type, [&](NamedDeclarations& decls)
    {
        auto decl = decls.find(name);

        if (decl != decls.end())
        {
            returnValue = decl->second;
        }
    });

    return returnValue;
}

IDeclaration::Ptr DeclarationManager::findOrCreateDeclaration(Type type, const std::string& name)
{
    IDeclaration::Ptr returnValue;

    doWithDeclarationLock(type, [&](NamedDeclarations& decls)
    {
        auto decl = decls.find(name);

        if (decl != decls.end())
        {
            returnValue = decl->second;
            return;
        }

        // Nothing found, acquire the lock to create the new decl
        // Check if we even know that type, otherwise throw
        if (_creatorsByType.count(type) == 0)
        {
            throw std::invalid_argument("Unregistered type " + getTypeName(type));
        }

        // Construct the default block
        DeclarationBlockSyntax syntax;

        syntax.typeName = getTypenameByType(type);
        syntax.name = name;
        // Derive the mod name from the path it can be written to
        syntax.modName = game::current::getModPath(game::current::getWriteableGameResourcePath());

        returnValue = createOrUpdateDeclaration(type, syntax);

        signal_DeclCreated().emit(type, name);
    });

    // If the value is still empty at this point, throw
    if (!returnValue)
    {
        throw std::invalid_argument("Unregistered type " + getTypeName(type));
    }

    return returnValue;
}

void DeclarationManager::foreachDeclaration(Type type, const std::function<void(const IDeclaration::Ptr&)>& functor)
{
    doWithDeclarationLock(type, [&](NamedDeclarations& decls)
    {
        for (const auto& [_, decl] : decls)
        {
            functor(decl);
        }
    });
}

void DeclarationManager::doWithDeclarationLock(Type type, const std::function<void(NamedDeclarations&)>& action)
{
    // All parsers should be done before doing anything with the declarations
    waitForTypedParsersToFinish();

    // Find type dictionary
    std::lock_guard declLock(_declarationAndCreatorLock);

    auto decls = _declarationsByType.find(type);

    if (decls == _declarationsByType.end()) return;

    action(decls->second.decls);
}

void DeclarationManager::reloadDeclarations()
{
    // Don't allow reloadDecls to be run before the startup phase is complete
    waitForTypedParsersToFinish();

    // Don't allow more than one simultaneous reloadDecls run
    if (_reparseInProgress) return;

    util::ScopedBoolLock reparseLock(_reparseInProgress);

    // Invoke the declsReloading signal for all types
    {
        std::lock_guard declLock(_declarationAndCreatorLock);

        for (const auto& [type, _] : _declarationsByType)
        {
            signal_DeclsReloading(type).emit();
        }
    }

    _parseStamp++;

    // Remove all unrecognised blocks from previous runs
    {
        std::lock_guard lock(_unrecognisedBlockLock);
        _unrecognisedBlocks.clear();
    }

    runParsersForAllFolders();

    {
        std::lock_guard lock(_parseResultLock);

        // Process the buffered results synchronously
        for (auto& [type, result] : _parseResults)
        {
            processParseResult(type, result);
        }

        _parseResults.clear();
    }

    std::vector<Type> typesToNotify;

    // Empty all declarations that haven't been touched during this reparse run
    {
        std::lock_guard declLock(_declarationAndCreatorLock);

        for (const auto& [_, namedDecls] : _declarationsByType)
        {
            for (const auto& [name, decl] : namedDecls.decls)
            {
                if (decl->getParseStamp() < _parseStamp)
                {
                    rMessage() << "[DeclManager] " << getTypeName(decl->getDeclType()) << " " <<
                        name << " no longer present after reloadDecls" << std::endl;

                    auto syntax = decl->getBlockSyntax();

                    // Clear name and file info
                    syntax.contents.clear();
                    syntax.fileInfo = vfs::FileInfo();

                    decl->setBlockSyntax(syntax);
                }
            }
        }

        // Invoke the declsReloaded signal for all types
        for (const auto& [type, _] : _declarationsByType)
        {
            typesToNotify.push_back(type);
        }
    }

    // Notify the clients with the lock released
    for (auto type : typesToNotify)
    {
        emitDeclsReloadedSignal(type);
    }
}

void DeclarationManager::waitForTypedParsersToFinish()
{
    {
        // Acquire the lock to modify the cleanup tasks list
        std::lock_guard declLock(_declarationAndCreatorLock);

        // Extract all parsers while we hold the lock
        std::vector<std::unique_ptr<DeclarationFolderParser>> parsersToFinish;

        for (auto& [_, decl] : _declarationsByType)
        {
            if (decl.parser)
            {
                parsersToFinish.emplace_back(std::move(decl.parser));
            }
        }

        if (!parsersToFinish.empty())
        {
            // Add the task to the list, we need to wait for it when shutting down the module
            // Move the collected parsers to the async lambda and clear it there
            _parserCleanupTasks.emplace_back(std::make_shared<std::shared_future<void>>(
                std::async(std::launch::async, [parsers = std::move(parsersToFinish)]() mutable
                {
                    // Without locking anything, just let all parsers finish their work
                    parsers.clear();
                })));
        }
    }

    // Let all running tasks finish
    waitForCleanupTasksToFinish();
}

void DeclarationManager::waitForCleanupTasksToFinish()
{
    while (true)
    {
        // Find the next cleanup task, but don't remove it from the list
        // Other threads might check the same list and get the impression there's nothing to wait for
        std::shared_ptr<std::shared_future<void>> task;

        {
            // Pick the next task to wait for
            std::lock_guard declLock(_declarationAndCreatorLock);

            if (_parserCleanupTasks.empty()) break; // Done

            for (const auto& candidate : _parserCleanupTasks)
            {
                if (candidate && candidate->valid() &&
                    candidate->wait_for(std::chrono::milliseconds(0)) != std::future_status::ready)
                {
                    task = candidate;
                    break;
                }
            }

            if (!task) return;
        }

        task->get(); // wait for this task, then enter the next round
    }
}

void DeclarationManager::waitForSignalInvokersToFinish()
{
    while (true)
    {
        // Pick the next task to wait for
        auto declLock = std::make_unique<std::lock_guard<std::recursive_mutex>>(_declarationAndCreatorLock);

        // No cleanup task found, check the tasks in the declaration structures
        std::future<void> signalInvoker;

        for (auto& [_, decl] : _declarationsByType)
        {
            if (decl.signalInvoker.valid())
            {
                signalInvoker = std::move(decl.signalInvoker);
                break;
            }
        }

        if (signalInvoker.valid())
        {
            declLock.reset();
            signalInvoker.get();
            continue;
        }

        return; // nothing more to do, we're done
    }
}

void DeclarationManager::runParsersForAllFolders()
{
    std::vector<std::unique_ptr<DeclarationFolderParser>> parsers;

    {
        std::lock_guard folderLock(_registeredFoldersLock);

        auto typeMapping = getTypenameMapping();

        // Start a parser for each known folder
        for (const auto& folder : _registeredFolders)
        {
            auto& parser = parsers.emplace_back(
                std::make_unique<DeclarationFolderParser>(*this, folder.defaultType, folder.folder, folder.extension, typeMapping)
            );
            parser->start();
        }
    }

    // Wait for all parsers to complete
    while (!parsers.empty())
    {
        parsers.back()->ensureFinished();
        parsers.pop_back();
    }
}

void DeclarationManager::removeDeclaration(Type type, const std::string& name)
{
    // All parsers need to have finished
    waitForTypedParsersToFinish();

    // Acquire the lock and perform the removal
    doWithDeclarationLock(type, [&](NamedDeclarations& decls)
    {
        auto decl = decls.find(name);

        if (decl != decls.end())
        {
            removeDeclarationFromFile(decl->second);

            // Clear out this declaration's syntax block
            auto syntax = decl->second->getBlockSyntax();
            syntax.name.clear();
            syntax.typeName.clear();
            syntax.contents.clear();
            syntax.fileInfo = vfs::FileInfo();
            decl->second->setBlockSyntax(syntax);

            decls.erase(decl);

            signal_DeclRemoved().emit(type, name);
        }
    });
}

namespace
{

bool removeDeclarationFromSyntaxTree(const parser::DefSyntaxTree::Ptr& syntaxTree, const std::string& declName)
{
    // Remove the declaration from the tree
    std::vector<parser::DefSyntaxNode::Ptr> nodesToRemove;

    const auto& childNodes = syntaxTree->getRoot()->getChildren();
    for (int i = 0; i < childNodes.size(); ++i)
    {
        const auto& node = childNodes.at(i);

        if (node->getType() != parser::DefSyntaxNode::Type::DeclBlock) continue;

        auto blockNode = std::static_pointer_cast<parser::DefBlockSyntax>(node);

        if (blockNode->getName() && blockNode->getName()->getToken().value == declName)
        {
            nodesToRemove.push_back(blockNode);

            parser::DefSyntaxNode::Ptr encounteredWhitespace;

            // Try to locate comment nodes preceding this block
            for (int p = i - 1; p >= 0; --p)
            {
                const auto& predecessor = childNodes.at(p);
                if (predecessor->getType() == parser::DefSyntaxNode::Type::Whitespace)
                {
                    // Stop at the first whitespace token that contains more than one line break
                    auto whitespace = std::static_pointer_cast<parser::DefWhitespaceSyntax>(predecessor);
                    
                    // stop searching at the first empty line
                    if (whitespace->getNumberOfLineBreaks() > 1) break;

                    // This is just a single line break (or none), remember to remove it when we encounter a comment
                    encounteredWhitespace = predecessor;
                }
                else if (predecessor->getType() == parser::DefSyntaxNode::Type::Comment)
                {
                    nodesToRemove.push_back(predecessor);

                    // Remove any whitespace that stood between this comment and the block
                    if (encounteredWhitespace)
                    {
                        nodesToRemove.push_back(encounteredWhitespace);
                        encounteredWhitespace.reset();
                    }

                    continue;
                }
                else // stop at all other node types
                {
                    break;
                }
            }
        }
    }

    for (const auto& node : nodesToRemove)
    {
        syntaxTree->getRoot()->removeChildNode(node);
    }

    return !nodesToRemove.empty(); // true if we removed one node or more
}

}

void DeclarationManager::removeDeclarationFromFile(const IDeclaration::Ptr& decl)
{
    const auto& syntax = decl->getBlockSyntax();

    // Nothing to do if the decl hasn't been saved
    if (syntax.fileInfo.name.empty()) return;

    if (!syntax.fileInfo.getIsPhysicalFile())
    {
        throw std::logic_error("Only declarations stored in physical files can be removed.");
    }

    auto fullPath = GlobalFileSystem().findFile(syntax.fileInfo.fullPath());

    if (fullPath.empty() || !fs::exists(fullPath))
    {
        return;
    }

    fullPath += syntax.fileInfo.fullPath();

    // Load the syntax tree from the existing file
    std::ifstream existingFile(fullPath);

    if (!existingFile.is_open())
    {
        throw std::runtime_error(fmt::format(_("Cannot open file for reading: {0}"), fullPath));
    }

    // Parse the existing file into a syntax tree for manipulation
    parser::DefBlockSyntaxParser<std::istream> parser(existingFile);
    
    auto syntaxTree = parser.parse();
    existingFile.close();

    // Try to remove the decl from the syntax tree (using the original name)
    // Returns false if the decl could not be located (decl has not been saved to this file then)
    if (removeDeclarationFromSyntaxTree(syntaxTree, decl->getOriginalDeclName()))
    {
        // Open a temporary file
        stream::TemporaryOutputStream tempStream(fullPath);
        auto& stream = tempStream.getStream();

        // Move the old file to .bak before overwriting it
        os::moveToBackupFile(fullPath);

        // Export the modified syntax tree
        stream << syntaxTree->getString();

        tempStream.closeAndReplaceTargetFile();
    }
}

bool DeclarationManager::renameDeclaration(Type type, const std::string& oldName_Incoming, const std::string& newName)
{
    auto result = false;

    if (oldName_Incoming == newName)
    {
        rWarning() << "Cannot rename, the new name is no different" << std::endl;
        return result;
    }

    // Create a local copy, the reference might point to the same string as the newName
    std::string oldName = oldName_Incoming;

    // Acquire the lock and perform the rename
    doWithDeclarationLock(type, [&](NamedDeclarations& decls)
    {
        auto decl = decls.find(newName);
        
        if (decl != decls.end())
        {
            rWarning() << "Cannot rename declaration to " << newName << " since this name is already in use" << std::endl;
            return;
        }

        // Look up the original declaration
        decl = decls.find(oldName);

        if (decl == decls.end())
        {
            rWarning() << "Cannot rename non-existent declaration " << oldName << std::endl;
            return;
        }

        // Rename in definition table
        auto extracted = decls.extract(oldName);
        extracted.key() = newName;

        decl = decls.insert(std::move(extracted)).position;

        // Store the new in the decl itself
        decl->second->setDeclName(newName);

        result = true;
    });

    if (result)
    {
        signal_DeclRenamed().emit(type, oldName, newName);
    }

    return result;
}

namespace
{

void ensureTargetFileExists(const std::string& targetFile, const std::string& relativePath)
{
    // If the file doesn't exist yet, let's check if we need to inherit stuff from the VFS
    if (fs::exists(targetFile)) return;

    auto inheritFile = GlobalFileSystem().openTextFile(relativePath);

    if (!inheritFile) return;

    // There is a file with that name already in the VFS, copy it to the target file
    TextInputStream& inheritStream = inheritFile->getInputStream();

    std::ofstream outFile(targetFile);

    if (!outFile.is_open())
    {
        throw std::runtime_error(fmt::format(_("Cannot open file for writing: {0}"), targetFile));
    }

    char buf[16384];
    std::size_t bytesRead = inheritStream.read(buf, sizeof(buf));

    while (bytesRead > 0)
    {
        outFile.write(buf, bytesRead);

        bytesRead = inheritStream.read(buf, sizeof(buf));
    }

    outFile.close();
}

}

void DeclarationManager::saveDeclaration(const IDeclaration::Ptr& decl)
{
    const auto& syntax = decl->getBlockSyntax();

    // Check filename for emptiness
    if (syntax.fileInfo.name.empty())
    {
        throw std::invalid_argument("The file name of the decl is empty.");
    }

    // All parsers need to have finished
    waitForTypedParsersToFinish();

    std::string relativePath = syntax.fileInfo.fullPath();

    fs::path targetPath = game::current::getWriteableGameResourcePath();

    // Ensure the target folder exists
    targetPath /= os::getDirectory(relativePath);
    fs::create_directories(targetPath);

    auto targetFile = targetPath / os::getFilename(syntax.fileInfo.name);

    // Make sure the physical file exists and is inheriting its contents from the VFS (if necessary)
    ensureTargetFileExists(targetFile.string(), relativePath);

    // Open a temporary file
    stream::TemporaryOutputStream tempStream(targetFile);

    auto& stream = tempStream.getStream();

    parser::DefSyntaxTree::Ptr syntaxTree;

    if (fs::exists(targetFile))
    {
        // Parse the existing file into a syntax tree for manipulation
        std::ifstream inheritStream(targetFile.string());

        parser::DefBlockSyntaxParser<std::istream> parser(inheritStream);

        syntaxTree = parser.parse();
        inheritStream.close();
    }
    else
    {
        // Since there's no existing file, create a new syntax tree
        syntaxTree = std::make_shared<parser::DefSyntaxTree>();
    }

    // Take the first named block matching our decl. There's a risk that there is another
    // decl of a different type with the same name in the tree, but we don't try to check this here
    auto block = syntaxTree->findFirstNamedBlock(decl->getOriginalDeclName());

    if (!block)
    {
        // Create a new block node with leading whitespace and add it to the tree
        syntaxTree->getRoot()->appendChildNode(parser::DefWhitespaceSyntax::Create("\n\n"));

        block = parser::DefBlockSyntax::CreateTypedBlock(syntax.typeName, decl->getDeclName());
        syntaxTree->getRoot()->appendChildNode(block);
    }

    // Check if the name of the decl has been changed
    if (decl->getDeclName() != decl->getOriginalDeclName())
    {
        // Update the name syntax node
        block->getName()->setName(decl->getDeclName());
    }

    // Store the new block contents and save the file
    block->setBlockContents(syntax.contents);

    // Export the modified syntax tree
    stream << syntaxTree->getString();

    tempStream.closeAndReplaceTargetFile();

    // Refresh the file info, otherwise a newly created file might not be considered "physical"
    // and declarations might report themselves as if they were originating in a PK4
    decl->setFileInfo(GlobalFileSystem().getFileInfo(relativePath));

    if (decl->getDeclName() != decl->getOriginalDeclName())
    {
        // Now that the decl is saved under a new name, update the original decl name
        decl->setOriginalDeclName(decl->getDeclName());
    }
}

sigc::signal<void>& DeclarationManager::signal_DeclsReloading(Type type)
{
    std::lock_guard lock(_signalAddLock);
    return _declsReloadingSignals.try_emplace(type).first->second;
}

sigc::signal<void>& DeclarationManager::signal_DeclsReloaded(Type type)
{
    std::lock_guard lock(_signalAddLock);
    return _declsReloadedSignals.try_emplace(type).first->second;
}

sigc::signal<void(Type, const std::string&, const std::string&)>& DeclarationManager::signal_DeclRenamed()
{
    return _declRenamedSignal;
}

sigc::signal<void(Type, const std::string&)>& DeclarationManager::signal_DeclCreated()
{
    return _declCreatedSignal;
}

sigc::signal<void(Type, const std::string&)>& DeclarationManager::signal_DeclRemoved()
{
    return _declRemovedSignal;
}

void DeclarationManager::emitDeclsReloadedSignal(Type type)
{
    signal_DeclsReloaded(type).emit();
}

void DeclarationManager::onParserFinished(Type parserType, ParseResult& parsedBlocks)
{
    if (_reparseInProgress)
    {
        std::lock_guard lock(_parseResultLock);

        // In the reparse scenario the results are processed synchronously
        // so buffer everything and let the reloadDeclarations() method
        // assign the blocks in the thread that started it.
        auto& pair = _parseResults.emplace_back(parserType, ParseResult());
        pair.second.swap(parsedBlocks);
    }
    else
    {
        // When not reloading, process the result immediately
        processParseResult(parserType, parsedBlocks);
    }

    // Move the parser reference out and wait for it to finish. Once the parser is gone,
    // the public API will be available to any callbacks the decls reloaded signal
    // is going to invoke. Since we're already on the parser thread
    // itself here, we need to do this on a separate thread to avoid deadlocks
    {
        std::lock_guard declLock(_declarationAndCreatorLock);

        auto decls = _declarationsByType.find(parserType);
        assert(decls != _declarationsByType.end());

        // Check if the parser reference is still there,
        // it might have already been moved out in doWithDeclarationLock()
        if (decls->second.parser)
        {
            // Move the parser reference from the dictionary as capture to the lambda
            // Then let the unique_ptr in the lambda go out of scope to finish off the thread
            // Lambda is mutable to make the unique_ptr member non-const
            decls->second.parserFinisher = std::async(std::launch::async, [p = std::move(decls->second.parser)]() mutable
            {
                p.reset();
            });
        }

        // In the reparse scenario the calling code will emit this signal
        // In the regular threaded scenario, the signal should fire on a separate thread
        if (!_reparseInProgress)
        {
            decls->second.signalInvoker = std::async(std::launch::async, [=]()
            {
                emitDeclsReloadedSignal(parserType);
            });
        }
    }
}

void DeclarationManager::processParseResult(Type parserType, ParseResult& parsedBlocks)
{
    // Sort all parsed blocks into our main dictionary
    // unrecognised blocks will be pushed to _unrecognisedBlocks
    processParsedBlocks(parsedBlocks);

    // Process the list of unrecognised blocks (from this and any previous run)
    handleUnrecognisedBlocks();
}

void DeclarationManager::processParsedBlocks(ParseResult& parsedBlocks)
{
    std::vector<DeclarationBlockSyntax> unrecognisedBlocks;

    {
        std::lock_guard declLock(_declarationAndCreatorLock);

        // Coming back from a parser thread, sort the parsed decls into the main dictionary
        for (auto& [type, blocks] : parsedBlocks)
        {
            for (auto& block : blocks)
            {
                if (type == Type::Undetermined)
                {
                    // Block type unknown, put it on the pile, it will be processed later
                    unrecognisedBlocks.emplace_back(std::move(block));
                    continue;
                }

                createOrUpdateDeclaration(type, block);
            }
        }
    }

    // With the _declarationLock and _creatorLock released, push blocks to the pile of unrecognised ones
    std::lock_guard lock(_unrecognisedBlockLock);
    _unrecognisedBlocks.insert(_unrecognisedBlocks.end(), std::make_move_iterator(unrecognisedBlocks.begin()),
        std::make_move_iterator(unrecognisedBlocks.end()));
}

bool DeclarationManager::tryDetermineBlockType(const DeclarationBlockSyntax& block, Type& type)
{
    type = Type::Undetermined;

    if (block.typeName.empty())
    {
        return false;
    }

    auto creator = _creatorsByTypename.find(block.typeName);

    if (creator == _creatorsByTypename.end())
    {
        return false;
    }

    // Found a creator that can handle this type
    type = creator->second->getDeclType();
    return true;
}

const IDeclaration::Ptr& DeclarationManager::createOrUpdateDeclaration(Type type, const DeclarationBlockSyntax& block)
{
    // Get the mapping for this decl type
    auto it = _declarationsByType.find(type);

    if (it == _declarationsByType.end())
    {
        it = _declarationsByType.emplace(type, Declarations()).first;
    }

    auto& map = it->second.decls;

    // See if this decl is already in use
    auto existing = map.find(block.name);

    // Create declaration if not existing
    if (existing == map.end())
    {
        auto creator = _creatorsByType.at(type);
        existing = map.emplace(block.name, creator->createDeclaration(block.name)).first;
    }
    else if (existing->second->getParseStamp() == _parseStamp)
    {
        rWarning() << "[DeclParser]: " << getTypeName(type) << " " <<
            existing->second->getDeclName() << " has already been declared" << std::endl;

        // Any declaration following after the first is ignored
        return existing->second;
    }

    // Assign the block to the declaration instance
    existing->second->setBlockSyntax(block);

    // Update the parse stamp for this instance
    existing->second->setParseStamp(_parseStamp);

    return existing->second;
}

void DeclarationManager::handleUnrecognisedBlocks()
{
    auto unrecognisedBlockLock = std::make_unique<std::lock_guard<std::recursive_mutex>>(_unrecognisedBlockLock);

    if (_unrecognisedBlocks.empty()) return;

    // Move all unrecognised blocks to a temporary structure and release the lock
    std::list<DeclarationBlockSyntax> unrecognisedBlocks(std::move(_unrecognisedBlocks));
    unrecognisedBlockLock.reset();

    {
        std::lock_guard declarationLock(_declarationAndCreatorLock);

        for (auto block = unrecognisedBlocks.begin(); block != unrecognisedBlocks.end();)
        {
            auto type = Type::Undetermined;

            if (!tryDetermineBlockType(*block, type))
            {
                ++block;
                continue;
            }

            createOrUpdateDeclaration(type, *block);

            unrecognisedBlocks.erase(block++);
        }
    }

    // All remaining unrecognised blocks are moved back to the pile
    unrecognisedBlockLock = std::make_unique<std::lock_guard<std::recursive_mutex>>(_unrecognisedBlockLock);
    _unrecognisedBlocks.insert(_unrecognisedBlocks.end(), std::move_iterator(unrecognisedBlocks.begin()),
        std::move_iterator(unrecognisedBlocks.end()));
}

std::string DeclarationManager::getTypenameByType(Type type)
{
    std::lock_guard declarationLock(_declarationAndCreatorLock);

    auto creator = _creatorsByType.at(type);

    for (const auto& [typeName, candidate] : _creatorsByTypename)
    {
        if (candidate == creator)
        {
            return typeName;
        }
    }

    throw std::invalid_argument("Unregistered type: " + getTypeName(type));
}

void DeclarationManager::onFilesystemInitialised()
{
    reloadDeclarations();
}

const std::string& DeclarationManager::getName() const
{
    static std::string _name(MODULE_DECLMANAGER);
    return _name;
}

const StringSet& DeclarationManager::getDependencies() const
{
    static StringSet _dependencies
    {
        MODULE_VIRTUALFILESYSTEM,
        MODULE_COMMANDSYSTEM,
    };

    return _dependencies;
}

void DeclarationManager::initialiseModule(const IApplicationContext& ctx)
{
    GlobalCommandSystem().addCommand("ReloadDecls",
        std::bind(&DeclarationManager::reloadDeclsCmd, this, std::placeholders::_1));

    // After the initial parsing, all decls will have a parseStamp of 0
    _parseStamp = 0;
    _reparseInProgress = false;

    _vfsInitialisedConn = GlobalFileSystem().signal_Initialised().connect(
        sigc::mem_fun(*this, &DeclarationManager::onFilesystemInitialised)
    );

    // Finish all pending threads before the modules are shut down
    // The push_front is a counter-action to the Map module subscribing to the same event
    module::GlobalModuleRegistry().signal_modulesUninitialising().slots().push_front([this]()
    {
        waitForTypedParsersToFinish();
        waitForSignalInvokersToFinish();
    });
}

void DeclarationManager::shutdownModule()
{
    _vfsInitialisedConn.disconnect();

    waitForTypedParsersToFinish();
    waitForSignalInvokersToFinish();

    // All parsers and tasks have finished, clear all structures, no need to lock anything
    _parserCleanupTasks.clear();
    _registeredFolders.clear();
    _unrecognisedBlocks.clear();
    _declarationsByType.clear();
    _creatorsByTypename.clear();
    _declsReloadingSignals.clear();
    _declsReloadedSignals.clear();
    _declRenamedSignal.clear();
    _declRemovedSignal.clear();
}

void DeclarationManager::reloadDeclsCmd(const cmd::ArgumentList& _)
{
    reloadDeclarations();
}

module::StaticModuleRegistration<DeclarationManager> _declManagerModule;

}