forked from Jenova-Framework/Jenova-Runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript_compiler.cpp
More file actions
2810 lines (2488 loc) · 143 KB
/
Copy pathscript_compiler.cpp
File metadata and controls
2810 lines (2488 loc) · 143 KB
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
/*-------------------------------------------------------------+
| |
| _________ ______ _ _____ |
| / / ____/ | / / __ \ | / / | |
| __ / / __/ / |/ / / / / | / / /| | |
| / /_/ / /___/ /| / /_/ /| |/ / ___ | |
| \____/_____/_/ |_/\____/ |___/_/ |_| |
| |
| Jenova Runtime |
| Developed by Hamid.Memar |
| |
+-------------------------------------------------------------*/
// Jenova SDK
#include "Jenova.hpp"
// Jenova Namespace
namespace jenova
{
// Windows Compilers
#ifdef TARGET_PLATFORM_WINDOWS
// Jenova Microsoft Visual C++ Compiler Implementation
class MicrosoftCompiler : public IJenovaCompiler
{
public:
MicrosoftCompiler(bool useLLVM)
{
// Set Sub-Compiler Model
compilerModel = useLLVM ? CompilerModel::ClangLLVMCompiler : CompilerModel::MicrosoftCompiler;
}
~MicrosoftCompiler()
{
}
bool InitializeCompiler(String compilerInstanceName = "<JenovaMSVCCompiler>")
{
// Microsoft Compiler Default Settings
if (this->GetCompilerModel() == CompilerModel::MicrosoftCompiler)
{
// Initialize Tool Chain Settings
internalDefaultSettings["instance_name"] = compilerInstanceName;
internalDefaultSettings["instance_version"] = 1.4f;
internalDefaultSettings["cpp_toolchain_path"] = "/Jenova/Compilers/JenovaMSVCCompiler";
internalDefaultSettings["cpp_compiler_binary"] = "/Bin/cl.exe";
internalDefaultSettings["cpp_linker_binary"] = "/Bin/link.exe";
internalDefaultSettings["cpp_include_path"] = "/Include";
internalDefaultSettings["cpp_library_path"] = "/Lib";
internalDefaultSettings["cpp_symbols_path"] = "/Symbols";
internalDefaultSettings["cpp_jenovasdk_path"] = "/Jenova/JenovaSDK";
internalDefaultSettings["cpp_godotsdk_path"] = "/Jenova/GodotSDK";
// MSVC Compiler Settings
internalDefaultSettings["cpp_language_standards"] = "cpp20"; /* /std:c++20 [cpp20, cpp17] */
internalDefaultSettings["cpp_clean_stack"] = true; /* /Gd */
internalDefaultSettings["cpp_intrinsic_functions"] = true; /* /Oi */
internalDefaultSettings["cpp_open_mp_support"] = true; /* /openmp */
internalDefaultSettings["cpp_multithreaded"] = true; /* /MT */
internalDefaultSettings["cpp_debug_database"] = true; /* /Zi */
internalDefaultSettings["cpp_conformance_mode"] = true; /* /permissive vs /permissive- */
internalDefaultSettings["cpp_exception_handling"] = 2; /* 1 : /EHsc 2: /EHa */
internalDefaultSettings["cpp_use_task_system"] = false; /* Internal Multiprocessing vs Task System */
internalDefaultSettings["cpp_extra_compiler"] = "/Ot /Ox /GR /bigobj"; /* Extra Compiler Options Like /Zc:threadSafeInit /Bt /Zc:tlsGuards /d1reportTime */
internalDefaultSettings["cpp_definitions"] = "TYPED_METHOD_BIND;HOT_RELOAD_ENABLED;_WINDLL";
// MSVC Linker Settings
internalDefaultSettings["cpp_output_module"] = "Jenova.Module.jnv"; /* Must use .dll for Debug .jnv for Final*/
internalDefaultSettings["cpp_output_map"] = "Jenova.Module.map";
internalDefaultSettings["cpp_output_database"] = "Jenova.Module.Database.pdb";
internalDefaultSettings["cpp_default_libs"] = "kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;delayimp.lib";
internalDefaultSettings["cpp_native_libs"] = "libGodot.x64.lib;";
internalDefaultSettings["cpp_delayed_dll"] = "/DELAYLOAD:\"Jenova.Runtime.Win64.dll\"";
internalDefaultSettings["cpp_default_subsystem"] = "Console"; /* /SUBSYSTEM:CONSOLE [Console, GUI]*/
internalDefaultSettings["cpp_machine_architecture"] = "Win64"; /* /MACHINE:X64 [Win64, Win32]*/
internalDefaultSettings["cpp_machine_pe_type"] = "dll"; /* /DLL [dll, exe]*/
internalDefaultSettings["cpp_add_manifest"] = true; /* /MANIFEST */
internalDefaultSettings["cpp_dynamic_base"] = true; /* /DYNAMICBASE */
internalDefaultSettings["cpp_debug_symbol"] = true; /* /DEBUG:FULL */
internalDefaultSettings["cpp_extra_linker"] = "/OPT:ICF /OPT:NOREF /LTCG"; /* Extra Linker Options */
}
// Microsoft Compiler LLVM Default Settings
if (this->GetCompilerModel() == CompilerModel::ClangLLVMCompiler)
{
// Initialize Tool Chain Settings
internalDefaultSettings["instance_name"] = compilerInstanceName;
internalDefaultSettings["instance_version"] = 1.4f;
internalDefaultSettings["cpp_toolchain_path"] = "/Jenova/Compilers/JenovaMSVCCompiler";
internalDefaultSettings["cpp_compiler_binary"] = "/Bin/clang-cl.exe";
internalDefaultSettings["cpp_linker_binary"] = "/Bin/lld-link.exe";
internalDefaultSettings["cpp_include_path"] = "/Include";
internalDefaultSettings["cpp_library_path"] = "/Lib";
internalDefaultSettings["cpp_symbols_path"] = "/Symbols";
internalDefaultSettings["cpp_jenovasdk_path"] = "/Jenova/JenovaSDK";
internalDefaultSettings["cpp_godotsdk_path"] = "/Jenova/GodotSDK";
// MSVC Compiler Settings
internalDefaultSettings["cpp_language_standards"] = "cpp20"; /* /std:c++20 [cpp20, cpp17] */
internalDefaultSettings["cpp_clean_stack"] = true; /* /Gd */
internalDefaultSettings["cpp_intrinsic_functions"] = true; /* /Oi */
internalDefaultSettings["cpp_open_mp_support"] = true; /* /openmp */
internalDefaultSettings["cpp_multithreaded"] = true; /* /MT */
internalDefaultSettings["cpp_debug_database"] = true; /* /Zi */
internalDefaultSettings["cpp_conformance_mode"] = true; /* /permissive vs /permissive- */
internalDefaultSettings["cpp_exception_handling"] = 2; /* 1 : /EHsc 2: /EHa */
internalDefaultSettings["cpp_use_task_system"] = true; /* Internal Multiprocessing vs Task System */
internalDefaultSettings["cpp_extra_compiler"] = "/Ot /Ox /GR /bigobj"; /* Extra Compiler Options Like /Zc:threadSafeInit /Bt /Zc:tlsGuards /d1reportTime */
internalDefaultSettings["cpp_definitions"] = "TYPED_METHOD_BIND;HOT_RELOAD_ENABLED;_WINDLL";
// MSVC Linker Settings
internalDefaultSettings["cpp_output_module"] = "Jenova.Module.jnv"; /* Must use .dll for Debug .jnv for Final*/
internalDefaultSettings["cpp_output_map"] = "Jenova.Module.map";
internalDefaultSettings["cpp_output_database"] = "Jenova.Module.Database.pdb";
internalDefaultSettings["cpp_default_libs"] = "kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;delayimp.lib";
internalDefaultSettings["cpp_native_libs"] = "libGodot.x64.lib;";
internalDefaultSettings["cpp_delayed_dll"] = "/DELAYLOAD:\"Jenova.Runtime.Win64.dll\"";
internalDefaultSettings["cpp_default_subsystem"] = "Console"; /* /SUBSYSTEM:CONSOLE [Console, GUI]*/
internalDefaultSettings["cpp_machine_architecture"] = "Win64"; /* /MACHINE:X64 [Win64, Win32]*/
internalDefaultSettings["cpp_machine_pe_type"] = "dll"; /* /DLL [dll, exe]*/
internalDefaultSettings["cpp_add_manifest"] = true; /* /MANIFEST */
internalDefaultSettings["cpp_dynamic_base"] = true; /* /DYNAMICBASE */
internalDefaultSettings["cpp_debug_symbol"] = true; /* /DEBUG:FULL */
internalDefaultSettings["cpp_extra_linker"] = "/OPT:ICF /OPT:NOREF /LTCG"; /* Extra Linker Options */
}
// All Good
return true;
}
bool ReleaseCompiler()
{
// Release Resources
internalDefaultSettings.clear();
return true;
}
String PreprocessScript(Ref<CPPScript> cppScript, const Dictionary& preprocessorSettings)
{
// Get Original Source Code
String scriptSourceCode = cppScript->get_source_code();
// Reset Line Number
scriptSourceCode = scriptSourceCode.insert(0, "#line 1\n");
// Process And Extract Properties
jenova::SerializedData propertiesMetadata = jenova::ProcessAndExtractPropertiesFromScript(scriptSourceCode, cppScript->GetScriptIdentity());
if (!propertiesMetadata.empty() && propertiesMetadata != "null") jenova::WriteStdStringToFile(AS_STD_STRING(String(preprocessorSettings["PropertyMetadata"])), propertiesMetadata);
// Preprocessor Definitions [Header]
String preprocessorDefinitions = "// Jenova Preprocessor Definitions\n";
// Preprocessor Definitions [Version]
preprocessorDefinitions += String(jenova::Format("#define JENOVA_VERSION \"%d.%d.%d.%d\"\n",
jenova::GlobalSettings::JenovaBuildVersion[0], jenova::GlobalSettings::JenovaBuildVersion[1],
jenova::GlobalSettings::JenovaBuildVersion[2], jenova::GlobalSettings::JenovaBuildVersion[3]).c_str());
// Preprocessor Definitions [Compiler]
if (this->GetCompilerModel() == CompilerModel::MicrosoftCompiler)
{
preprocessorDefinitions += "#define JENOVA_COMPILER \"Microsoft Visual C++ Compiler\"\n";
preprocessorDefinitions += "#define MSVC_COMPILER\n";
}
if (this->GetCompilerModel() == CompilerModel::ClangLLVMCompiler)
{
preprocessorDefinitions += "#define JENOVA_COMPILER \"Microsoft Visual C++ Compiler LLVM\"\n";
preprocessorDefinitions += "#define MSVC_LLVM_COMPILER\n";
}
// Preprocessor Definitions [Linking]
if (jenova::GlobalStorage::SDKLinkingMode == SDKLinkingMode::Statically) preprocessorDefinitions += "#define JENOVA_SDK_STATIC_LINKING\n";
if (jenova::GlobalStorage::SDKLinkingMode == SDKLinkingMode::Dynamically) preprocessorDefinitions += "#define JENOVA_SDK_DYNAMIC_LINKING\n";
// Preprocessor Definitions [User]
String userPreprocessorDefinitions = preprocessorSettings["PreprocessorDefinitions"];
PackedStringArray userPreprocessorDefinitionsList = userPreprocessorDefinitions.split(";");
for (const auto& definition : userPreprocessorDefinitionsList) if (!definition.is_empty()) preprocessorDefinitions += "#define " + definition + "\n";
// Add Final Preprocessor Definitions
scriptSourceCode = scriptSourceCode.insert(0, preprocessorDefinitions + "\n");
// Replecements
scriptSourceCode = scriptSourceCode.replace(jenova::GlobalSettings::ScriptToolIdentifier, "#define TOOL_SCRIPT");
scriptSourceCode = scriptSourceCode.replace(jenova::GlobalSettings::ScriptBlockBeginIdentifier, "namespace JNV_" + cppScript->GetScriptIdentity() + " {");
scriptSourceCode = scriptSourceCode.replace(jenova::GlobalSettings::ScriptBlockEndIdentifier, "}; using namespace JNV_" + cppScript->GetScriptIdentity() + ";");
scriptSourceCode = scriptSourceCode.replace(" OnReady", " _ready");
scriptSourceCode = scriptSourceCode.replace(" OnAwake", " _enter_tree");
scriptSourceCode = scriptSourceCode.replace(" OnDestroy", " _exit_tree");
scriptSourceCode = scriptSourceCode.replace(" OnProcess", " _process");
scriptSourceCode = scriptSourceCode.replace(" OnPhysicsProcess", " _physics_process");
scriptSourceCode = scriptSourceCode.replace(" OnInput", " _input");
scriptSourceCode = scriptSourceCode.replace(" OnUserInterfaceInput", " _gui_input");
// Return Preprocessed Source
return scriptSourceCode;
}
CompileResult CompileScript(const String sourceCode)
{
return CompileScriptWithCustomSettings(sourceCode, this->internalDefaultSettings);
}
CompileResult CompileScriptWithCustomSettings(const String sourceCode, const Dictionary& compilerSettings)
{
CompileResult result;
result.hasError = true;
result.compileError = "This Compiler does not support Compilation from Memory!";
return result;
}
CompileResult CompileScriptFromFile(const String scriptFilePath)
{
return CompileScriptFromFileWithCustomSettings(scriptFilePath, this->internalDefaultSettings);
}
CompileResult CompileScriptFromFileWithCustomSettings(const String scriptFilePath, const Dictionary& compilerSettings)
{
CompileResult result;
result.hasError = true;
result.compileError = "The requested compilation method is currently Not Implemented.";
return result;
}
CompileResult CompileScriptModuleContainer(const ScriptModuleContainer& scriptModulesContainer)
{
return CompileScriptModuleWithCustomSettingsContainer(scriptModulesContainer, this->internalDefaultSettings);
}
CompileResult CompileScriptModuleWithCustomSettingsContainer(const ScriptModuleContainer& scriptModulesContainer, const Dictionary& compilerSettings)
{
// Create Compiler Result
CompileResult result;
// Solve Settings [Cache]
if (!SolveCompilerSettings(compilerSettings))
{
result.compileResult = false;
result.hasError = true;
result.compileError = "C666 : Unable to Solve Compiler Settings.";
return result;
};
// Utilities
auto GeneratePreprocessDefinitions = [](const godot::String& defsSetting) -> std::string
{
std::string defs = AS_STD_STRING(defsSetting);
if (defs.empty()) return "";
if (defs.back() == ';') defs.pop_back();
std::vector<std::string> defsArray;
size_t start = 0;
size_t end = defs.find(';');
while (end != std::string::npos)
{
defsArray.push_back(defs.substr(start, end - start));
start = end + 1;
end = defs.find(';', start);
}
defsArray.push_back(defs.substr(start));
std::string result;
for (const auto& def : defsArray) result += "/D \"" + def + "\" ";
return result;
};
auto GenerateAdditionalIncludeDirectories = [](const godot::String& additionalDirs) -> std::string
{
std::string dirs = AS_STD_STRING(additionalDirs);
if (dirs.empty()) return "";
if (dirs.back() == ';') dirs.pop_back();
std::vector<std::string> dirArray;
size_t start = 0;
size_t end = dirs.find(';');
while (end != std::string::npos)
{
dirArray.push_back(dirs.substr(start, end - start));
start = end + 1;
end = dirs.find(';', start);
}
dirArray.push_back(dirs.substr(start));
std::string result;
for (const auto& dir : dirArray) result += "/I \"" + dir + "\" ";
return result;
};
// Generate Compiler Arguments
std::string compilerArgument;
compilerArgument += "\"" + this->compilerBinaryPath + "\" /c ";
if (String(compilerSettings["cpp_language_standards"]) == "cpp23") compilerArgument += "/std:c++23 ";
if (String(compilerSettings["cpp_language_standards"]) == "cpp20") compilerArgument += "/std:c++20 ";
if (String(compilerSettings["cpp_language_standards"]) == "cpp17") compilerArgument += "/std:c++17 ";
if (bool(compilerSettings["cpp_clean_stack"])) compilerArgument += "/Gd ";
if (bool(compilerSettings["cpp_intrinsic_functions"])) compilerArgument += "/Oi ";
if (bool(compilerSettings["cpp_open_mp_support"])) compilerArgument += "/openmp ";
if (bool(compilerSettings["cpp_multithreaded"])) compilerArgument += "/MT ";
if (bool(compilerSettings["cpp_debug_database"]) && bool(compilerSettings["cpp_generate_debug_info"]))
{
compilerArgument += "/Zi ";
compilerArgument += "/Fd\"" + this->jenovaCachePath + AS_STD_STRING(String(compilerSettings["cpp_output_database"])) + "\" ";;
}
compilerArgument += bool(compilerSettings["cpp_conformance_mode"]) ? "/permissive- " : "/permissive ";
if (int(compilerSettings["cpp_exception_handling"]) == 1) compilerArgument += "/EHsc ";
if (int(compilerSettings["cpp_exception_handling"]) == 2) compilerArgument += "/EHa ";
if (QUERY_SDK_LINKING_MODE(Statically)) compilerArgument += "/D \"JENOVA_SDK_STATIC\" ";
compilerArgument += GeneratePreprocessDefinitions(compilerSettings["cpp_definitions"]);
compilerArgument += "/I \"./\" ";
compilerArgument += "/I \"" + this->includePath + "\" ";
compilerArgument += "/I \"" + this->jenovaSDKPath + "\" ";
compilerArgument += "/I \"" + this->godotSDKPath + "\" ";
// Add Additional Include Directories
compilerArgument += GenerateAdditionalIncludeDirectories(compilerSettings["cpp_extra_include_directories"]);
// Add Packages Headers (Addons, Libraries etc.)
for (const auto& addonConfig : jenova::GetInstalledAddones())
{
// Check For Addon Type
if (addonConfig.Type == "RuntimeModule")
{
if (!addonConfig.Header.empty())
{
if (addonConfig.Global)
{
std::string headerPath = addonConfig.Path + "/" + addonConfig.Header;
compilerArgument += "/FI \"" + headerPath + "\" ";
}
compilerArgument += "/I \"" + addonConfig.Path + "\" ";
}
}
}
// Disable Logo
compilerArgument += "/nologo ";
// Load Cache if Exists
bool buildCacheFileFound = false;
nlohmann::json buildCacheDatabase;
if (!std::filesystem::exists(this->jenovaCachePath + jenova::GlobalSettings::JenovaBuildCacheDatabaseFile))
{
// Cache Doesn't Exists Generate It [Required for Proxies]
if (!jenova::CreateBuildCacheDatabase(this->jenovaCachePath + jenova::GlobalSettings::JenovaBuildCacheDatabaseFile, scriptModulesContainer.scriptModules, compilerSettings["CppHeaderFiles"], true))
{
result.compileResult = false;
result.hasError = true;
result.compileError = "C670 : Failed to Generate Build Cache Database.";
return result;
}
}
// Parse Cache File
try
{
std::ifstream buildCacheDatabaseReader(this->jenovaCachePath + jenova::GlobalSettings::JenovaBuildCacheDatabaseFile, std::ios::binary);
std::string buildCacheDatabaseContent(std::istreambuf_iterator<char>(buildCacheDatabaseReader), {});
if (!buildCacheDatabaseContent.empty())
{
buildCacheDatabase = nlohmann::json::parse(buildCacheDatabaseContent);
buildCacheFileFound = true;
}
}
catch (const std::exception&)
{
result.compileResult = false;
result.hasError = true;
result.compileError = "C671 : Failed to Parse Build Cache Database.";
return result;
}
// Check If Any Changes Applied to Headers
if (buildCacheDatabase.contains("Headers"))
{
// Detect Changes
bool detectedHeaderChanges = false;
PackedStringArray cppHeaderFiles = compilerSettings["CppHeaderFiles"];
for (const auto& cppHeaderFile : cppHeaderFiles)
{
String cppHeaderUID = jenova::GenerateStandardUIDFromPath(cppHeaderFile);
String cppHeaderHash = jenova::GenerateMD5HashFromFile(cppHeaderFile);
if (buildCacheDatabase["Headers"].contains(AS_STD_STRING(cppHeaderUID)))
{
if (AS_STD_STRING(cppHeaderHash) != buildCacheDatabase["Headers"][AS_STD_STRING(cppHeaderUID)].get<std::string>())
{
detectedHeaderChanges = true;
break;
}
}
}
if (buildCacheDatabase.contains("HeaderCount"))
{
int headerCount = buildCacheDatabase["HeaderCount"].get<int>();
if (headerCount != cppHeaderFiles.size()) detectedHeaderChanges = true;
}
// If Contains Changes Reset All Script Cache
if (detectedHeaderChanges)
{
if (buildCacheDatabase.contains("Modules")) for (const auto& scriptModule : buildCacheDatabase["Modules"].items()) scriptModule.value() = "No Hash";
}
}
// Add Source/Output Based On Compile Model
jenova::ModuleList compilationScripts;
if (bool(compilerSettings["cpp_multi_threaded_compilation"]))
{
for (const auto& scriptModule : scriptModulesContainer.scriptModules)
{
// Skip If File Hash Didn't Change
if (buildCacheDatabase.contains("Modules"))
{
if (buildCacheDatabase["Modules"].contains(AS_STD_STRING(scriptModule.scriptUID)))
{
if (AS_STD_STRING(scriptModule.scriptHash) == buildCacheDatabase["Modules"][AS_STD_STRING(scriptModule.scriptUID)].get<std::string>()) continue;
}
}
// Add Source
compilationScripts.push_back(scriptModule);
// Add Script Count
result.scriptsCount++;
}
}
else
{
// If Script Has Changes Add to Compilation Scripts
if (buildCacheDatabase.contains("Modules"))
{
if (buildCacheDatabase["Modules"].contains(AS_STD_STRING(scriptModulesContainer.scriptModule.scriptUID)))
{
if (AS_STD_STRING(scriptModulesContainer.scriptModule.scriptHash) != buildCacheDatabase["Modules"][AS_STD_STRING(scriptModulesContainer.scriptModule.scriptUID)].get<std::string>())
{
compilationScripts.push_back(scriptModulesContainer.scriptModule);
result.scriptsCount++;
}
}
}
}
// Skip Compile If Source Count is 0
if (result.scriptsCount == 0)
{
result.compileResult = true;
result.hasError = false;
result.compileVerbose = "Cache System Detected No Script Requires to be Compiled.";
return result;
}
// Add Extra Options
compilerArgument += AS_STD_STRING(String(compilerSettings["cpp_extra_compiler"])) + " ";
// Dump Compiler Command If Developer Mode Enabled
if (jenova::GlobalStorage::DeveloperModeActivated) jenova::WriteStdStringToFile(jenovaCachePath + "CompilerCommand.txt", compilerArgument);
// Handle Multi Process Compilation
if (bool(compilerSettings["cpp_multi_threaded_compilation"]))
{
// Using Task System
if (bool(compilerSettings["cpp_use_task_system"]))
{
// Verbose Multi Processing Model
jenova::Output("Using Task System for Multi-Processing...");
// Compile Scripts
std::vector<jenova::TaskID> compilationTasks;
bool compilationFailed = false;
std::mutex compilationMutex;
std::vector<std::string> errorMessages;
// Spawn Tasks Per Script
for (const auto& scriptModule : compilationScripts)
{
std::string command = compilerArgument;
command += "\"" + AS_STD_STRING(scriptModule.scriptCacheFile) + "\" ";
command += "-o \"" + AS_STD_STRING(scriptModule.scriptObjectFile) + "\" ";
// Fix Paths in Command
jenova::ReplaceAllMatchesWithString(command, "\\", "/");
jenova::ReplaceAllMatchesWithString(command, "\\\\", "/");
// Initiate Compilation Task
jenova::TaskID taskID = JenovaTaskSystem::InitiateTask([command, &compilationFailed, &compilationMutex, &errorMessages]()
{
STARTUPINFOW si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
si.dwFlags |= STARTF_USESTDHANDLES;
HANDLE hStdOutRead, hStdOutWrite;
SECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
CreatePipe(&hStdOutRead, &hStdOutWrite, &sa, 0);
SetHandleInformation(hStdOutRead, HANDLE_FLAG_INHERIT, 0);
si.hStdOutput = hStdOutWrite;
si.hStdError = hStdOutWrite;
std::wstring wCommand(command.begin(), command.end());
if (!CreateProcessW(NULL, &wCommand[0], NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
{
std::lock_guard<std::mutex> lock(compilationMutex);
compilationFailed = true;
errorMessages.push_back("Failed to start compilation process.");
return;
}
CloseHandle(hStdOutWrite);
std::vector<char> buffer(4096);
DWORD bytesRead;
std::string compilerOutput;
while (ReadFile(hStdOutRead, buffer.data(), buffer.size(), &bytesRead, NULL) && bytesRead > 0)
{
compilerOutput.append(buffer.data(), bytesRead);
}
CloseHandle(hStdOutRead);
WaitForSingleObject(pi.hProcess, INFINITE);
DWORD exitCode;
GetExitCodeProcess(pi.hProcess, &exitCode);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
if (exitCode != 0)
{
std::lock_guard<std::mutex> lock(compilationMutex);
compilationFailed = true;
errorMessages.push_back(compilerOutput);
}
});
compilationTasks.push_back(taskID);
}
// Wait for all tasks to complete
for (const auto& taskID : compilationTasks)
{
while (!JenovaTaskSystem::IsTaskComplete(taskID))
{
std::this_thread::yield();
}
JenovaTaskSystem::ClearTask(taskID);
}
// Check Compile Result
if (compilationFailed)
{
result.compileResult = false;
result.hasError = true;
result.compileError = "C668 : One or more compilation tasks failed.\n";
for (const auto& errorMsg : errorMessages)
{
result.compileError += String(errorMsg.c_str()) + "\n";
}
return result;
}
// Set Compiler Result
result.compileResult = !compilationFailed;
result.hasError = !compilationFailed;
// Yield Engine
OS::get_singleton()->delay_msec(1);
std::this_thread::yield();
// Return Final Result
return result;
}
// Using Internal Multiprocessing
else
{
// Verbose Multi Processing Model
jenova::Output("Using Compiler Native Multi-Processing...");
// Set Compiler Multi-Processing Mode & Set Output
compilerArgument += "/MP ";
compilerArgument += "/Fo\"" + this->jenovaCachePath + "\" ";
// Add Compilation Scripts to Compiler Argument
for (const auto& scriptModule : compilationScripts)
{
// Add Source
compilerArgument += "\"" + AS_STD_STRING(scriptModule.scriptCacheFile) + "\" ";
}
}
}
// Handle Single Thread Compilation
if (!bool(compilerSettings["cpp_multi_threaded_compilation"]))
{
compilerArgument += "\"" + AS_STD_STRING(scriptModulesContainer.scriptModule.scriptCacheFile) + "\" ";
compilerArgument += "/Fo\"" + AS_STD_STRING(scriptModulesContainer.scriptModule.scriptObjectFile) + "\" ";
}
// Run Compiler
STARTUPINFOW si = { 0 };
PROCESS_INFORMATION pi;
si.cb = sizeof(si);
si.dwFlags |= STARTF_USESTDHANDLES;
// Create pipes for capturing output
HANDLE hStdOutRead, hStdOutWrite;
SECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
CreatePipe(&hStdOutRead, &hStdOutWrite, &sa, 0);
SetHandleInformation(hStdOutRead, HANDLE_FLAG_INHERIT, 0);
si.hStdOutput = hStdOutWrite;
si.hStdError = hStdOutWrite;
// Convert command to wide string
std::wstring wCompilerArgument(compilerArgument.begin(), compilerArgument.end());
// Execute the command
if (!CreateProcessW(NULL, &wCompilerArgument[0], NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
{
result.compileResult = false;
result.hasError = true;
result.compileError = "C667 : Failed to Run Compiler!";
return result;
}
// Close write end of the pipe
CloseHandle(hStdOutWrite);
// Read And Filter Output
std::vector<char> buffer(jenova::GlobalSettings::BuildOutputBufferSize);
DWORD bytesRead;
std::string resultOutput, accumulatedOutput;
while (ReadFile(hStdOutRead, buffer.data(), buffer.size(), &bytesRead, NULL) && bytesRead > 0)
{
accumulatedOutput.append(buffer.data(), bytesRead);
std::istringstream stream(accumulatedOutput);
std::string line;
std::regex pathRegex("(.*)\\((\\d+)\\): (.*)");
std::smatch match;
std::string remainingOutput;
// Parse Lines
while (std::getline(stream, line))
{
// If Incomplete, Save it for Next Read
if (stream.eof() && !line.empty() && accumulatedOutput.back() != '\n')
{
remainingOutput = line;
break;
}
// Checks for time() Lines
if (line.find("time(") != std::string::npos) continue;
// Check for Source File
if (line.size() >= 6 && line.compare(line.size() - 5, 5, ".cpp\r") == 0)
{
// Skip Source Lines
continue;
}
// Replace Paths with At Line
if (std::regex_search(line, match, pathRegex))
{
std::string proxyFileName = std::filesystem::path(match[1].str()).filename().string();
if (buildCacheDatabase["Proxies"].contains(proxyFileName))
{
std::string actualSourceFile = buildCacheDatabase["Proxies"][proxyFileName].get<std::string>();
std::string newLine = "Script [" + actualSourceFile + "] Line " + match[2].str() + " :: " + match[3].str() + "\n";
resultOutput.append(newLine);
continue;
}
}
// Other Lines
resultOutput.append(line + "\n");
}
// Save the remaining output for the next read
accumulatedOutput = remainingOutput;
}
if (!resultOutput.empty() && resultOutput.back() == '\n') resultOutput.pop_back();
// Wait for the process to finish
WaitForSingleObject(pi.hProcess, INFINITE);
// Get the exit code
DWORD exitCode;
GetExitCodeProcess(pi.hProcess, &exitCode);
// Close handles
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
CloseHandle(hStdOutRead);
// Set the compiler result
result.compileResult = (exitCode == 0);
result.hasError = (exitCode != 0);
result.compileError = String(resultOutput.c_str());
result.compileVerbose = String(resultOutput.c_str());
// Yield Engine
OS::get_singleton()->delay_msec(1);
std::this_thread::yield();
// Return Final Result
return result;
}
BuildResult BuildFinalModule(const jenova::ModuleList& scriptModules)
{
return BuildFinalModuleWithCustomSettings(scriptModules, internalDefaultSettings);
}
BuildResult BuildFinalModuleWithCustomSettings(const jenova::ModuleList& scriptModules, const Dictionary& linkerSettings)
{
// Create Build Result
BuildResult result;
// Solve Settings [Cache]
if (!SolveCompilerSettings(linkerSettings))
{
result.buildResult = false;
result.hasError = true;
result.buildError = "L666 : Unable to Solve Linker Settings.";
return result;
};
// Set Output Directory Path on Build Result
result.buildPath = this->jenovaCachePath;
// Set Compiler Model
result.compilerModel = this->GetCompilerModel();
// Set Debug Information Flag
result.hasDebugInformation = bool(linkerSettings["cpp_generate_debug_info"]);
// Generate Output Module Path
std::string outputModule = this->jenovaCachePath + (result.hasDebugInformation ? "Jenova.Module.dll" : AS_STD_STRING((String)linkerSettings["cpp_output_module"]));
std::string outputMap = this->jenovaCachePath + AS_STD_STRING((String)linkerSettings["cpp_output_map"]);
// Utilities
auto GenerateLibraries = [](const godot::String& libsSetting) -> std::string
{
std::string libs = AS_STD_STRING(libsSetting);
if (libs.empty()) return "";
if (libs.back() == ';') libs.pop_back();
std::vector<std::string> libsArray;
size_t start = 0;
size_t end = libs.find(';');
while (end != std::string::npos)
{
libsArray.push_back(libs.substr(start, end - start));
start = end + 1;
end = libs.find(';', start);
}
libsArray.push_back(libs.substr(start));
std::string result;
for (const auto& lib : libsArray) result += "\"" + lib + "\" ";
return result;
};
auto GenerateAdditionalLibraryDirectories = [](const godot::String& additionalDirs) -> std::string
{
std::string dirs = AS_STD_STRING(additionalDirs);
if (dirs.empty()) return "";
if (dirs.back() == ';') dirs.pop_back();
std::vector<std::string> dirArray;
size_t start = 0;
size_t end = dirs.find(';');
while (end != std::string::npos)
{
dirArray.push_back(dirs.substr(start, end - start));
start = end + 1;
end = dirs.find(';', start);
}
dirArray.push_back(dirs.substr(start));
std::string result;
for (const auto& dir : dirArray) result += "/LIBPATH:\"" + dir + "\" ";
return result;
};
// Generate Linker Arguments
std::string linkerArgument;
linkerArgument += "\"" + this->linkerBinaryPath + "\" ";
linkerArgument += "/OUT:\"" + outputModule + "\" ";
linkerArgument += "/MAP:\"" + outputMap + "\" ";
if (String(linkerSettings["cpp_default_subsystem"]) == "Console") linkerArgument += "/SUBSYSTEM:CONSOLE ";
if (String(linkerSettings["cpp_default_subsystem"]) == "GUI") linkerArgument += "/SUBSYSTEM:WINDOWS ";
if (String(linkerSettings["cpp_machine_architecture"]) == "Win64") linkerArgument += "/MACHINE:X64 ";
if (String(linkerSettings["cpp_machine_architecture"]) == "Win32") linkerArgument += "/MACHINE:X86 ";
if (String(linkerSettings["cpp_machine_pe_type"]) == "dll") linkerArgument += "/DLL ";
if (String(linkerSettings["cpp_machine_pe_type"]) == "exe") linkerArgument += "/EXE ";
if (bool(linkerSettings["cpp_add_manifest"])) linkerArgument += "/MANIFEST ";
if (bool(linkerSettings["cpp_dynamic_base"])) linkerArgument += "/DYNAMICBASE ";
if (bool(linkerSettings["cpp_debug_symbol"]) && result.hasDebugInformation) linkerArgument += "/DEBUG:FULL ";
linkerArgument += GenerateLibraries(linkerSettings["cpp_default_libs"]);
linkerArgument += GenerateLibraries(linkerSettings["cpp_native_libs"]);
linkerArgument += GenerateLibraries(linkerSettings["cpp_extra_libs"]);
linkerArgument += "/LIBPATH:\"./\" ";
linkerArgument += "/LIBPATH:\"" + this->libraryPath + "\" ";
linkerArgument += "/LIBPATH:\"" + this->jenovaSDKPath + "\" ";
linkerArgument += "/LIBPATH:\"" + this->godotSDKPath + "\" ";
// Handle JenovaSDK Linking
if (QUERY_SDK_LINKING_MODE(Dynamically)) linkerArgument += "Jenova.SDK.x64.lib ";
if (QUERY_SDK_LINKING_MODE(Statically)) linkerArgument += "Jenova.SDK.Static.x64.lib ";
// Add Additional Library Directories
linkerArgument += GenerateAdditionalLibraryDirectories(linkerSettings["cpp_extra_library_directories"]);
// Add Packages Libraries (Addons, Libraries etc.)
for (const auto& addonConfig : jenova::GetInstalledAddones())
{
// Check For Addon Type
if (addonConfig.Type == "RuntimeModule")
{
if (!addonConfig.Header.empty())
{
std::string libraryPath = addonConfig.Path + "/" + addonConfig.Library;
linkerArgument += "\"" + libraryPath + "\" ";
linkerArgument += "/DELAYLOAD:\"" + addonConfig.Binary + "\" ";
}
}
}
// Disable Logo
linkerArgument += "/nologo ";
// Ignore Warnings
linkerArgument += "/IGNORE:4099 ";
// Add Object Files
for (const auto& scriptModule : scriptModules) linkerArgument += "\"" + AS_STD_STRING(scriptModule.scriptObjectFile) + "\" ";
// Add Extra Options
linkerArgument += AS_STD_STRING(String(linkerSettings["cpp_extra_linker"])) + " ";
// Add Delayed DLLs
if (QUERY_SDK_LINKING_MODE(Dynamically)) linkerArgument += AS_STD_STRING(String(linkerSettings["cpp_delayed_dll"])) + " ";
// Dump Linker Command If Developer Mode Enabled
if (jenova::GlobalStorage::DeveloperModeActivated) jenova::WriteStdStringToFile(jenovaCachePath + "LinkerCommand.txt", linkerArgument);
// Run Linker
STARTUPINFOW si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
si.dwFlags |= STARTF_USESTDHANDLES;
// Create pipes for capturing output
HANDLE hStdOutRead, hStdOutWrite;
SECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
CreatePipe(&hStdOutRead, &hStdOutWrite, &sa, 0);
SetHandleInformation(hStdOutRead, HANDLE_FLAG_INHERIT, 0);
si.hStdOutput = hStdOutWrite;
si.hStdError = hStdOutWrite;
// Convert linker command to wide string
std::wstring wLinkerArgument(linkerArgument.begin(), linkerArgument.end());
// Execute the linker command
if (!CreateProcessW(NULL, &wLinkerArgument[0], NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
{
result.buildResult = false;
result.hasError = true;
result.buildError = "L667 : Failed to Run Linker!";
return result;
}
// Close the write end of the pipe
CloseHandle(hStdOutWrite);
// Read the linker output
std::vector<char> buffer(jenova::GlobalSettings::BuildOutputBufferSize);
DWORD bytesRead;
std::string resultOutput;
while (ReadFile(hStdOutRead, buffer.data(), buffer.size(), &bytesRead, NULL) && bytesRead > 0) resultOutput.append(buffer.data(), bytesRead);
// Wait for the process to finish
WaitForSingleObject(pi.hProcess, INFINITE);
// Get the exit code of the linker process
DWORD exitCode;
GetExitCodeProcess(pi.hProcess, &exitCode);
// Close handles
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
CloseHandle(hStdOutRead);
// Set the build result
result.buildResult = (exitCode == 0);
result.hasError = (exitCode != 0);
result.buildError = String(resultOutput.c_str());
result.buildVerbose = String(resultOutput.c_str());
// Return if There's error
if (!result.buildResult) return result;
// Read module to buffer
std::ifstream moduleReader(outputModule, std::ios::binary);
result.builtModuleData = std::vector<uint8_t>(std::istreambuf_iterator<char>(moduleReader), {});
// Validate Module Buffer
if (result.builtModuleData.size() == 0)
{
result.buildResult = false;
result.hasError = true;
result.buildError = "L668 : Invalid Module Data.";
return result;
}
// Generate Metadata
result.moduleMetaData = JenovaInterpreter::GenerateModuleMetadata(outputMap, scriptModules, result);
if (result.moduleMetaData.empty())
{
result.buildResult = false;
result.hasError = true;
result.buildError = "L669 : Failed to Generate Module Meta Data.";
return result;
}
// Generate Build Cache
if (!jenova::CreateBuildCacheDatabase(this->jenovaCachePath + jenova::GlobalSettings::JenovaBuildCacheDatabaseFile, scriptModules, linkerSettings["CppHeaderFiles"]))
{
result.buildResult = false;
result.hasError = true;
result.buildError = "L670 : Failed to Generate Build Cache Database.";
return result;
}
// Yield Engine
OS::get_singleton()->delay_msec(1);
std::this_thread::yield();
// Return Final Result
return result;
}
bool SetCompilerOption(const String& optName, const Variant& optValue)
{
internalDefaultSettings[optName] = optValue;
return true;
}
Variant GetCompilerOption(const String& optName) const
{
if (internalDefaultSettings.has(optName)) return internalDefaultSettings[optName];
return Variant();
}
Variant ExecuteCommand(const String& commandName, const Dictionary& commandSettings)
{
// Process Commands
if (commandName == "Solve-Compiler-Settings")
{
return SolveCompilerSettings(internalDefaultSettings);
}
// Invalid Command
return Variant::NIL;
}
CompilerFeatures GetCompilerFeatures() const
{
return CanCompileFromFile | CanGenerateMappingData | CanGenerateModule | CanLinkObjectFiles;
}
CompilerModel GetCompilerModel() const
{
return compilerModel;
}
bool SolveCompilerSettings(const Dictionary& compilerSettings)
{
// Get Project Path
String projectPath = jenova::GetJenovaProjectDirectory();
// Collect Compiler & GodotKit Packages
String selectedCompilerPath = jenova::GetInstalledCompilerPathFromPackages(compilerSettings["cpp_toolchain_path"], GetCompilerModel());
String selectedGodotKitPath = jenova::GetInstalledGodotKitPathFromPackages(compilerSettings["cpp_godotsdk_path"]);
// Validate Compiler & GodotKit Packages
if (selectedCompilerPath == "Missing-Compiler-1.0.0")
{
jenova::Error("Jenova Microsoft Compiler", "No Microsoft Compiler Detected On Build System, Install At Least One From Package Manager!");
return false;
}
if (selectedGodotKitPath == "Missing-GodotKit-1.0.0")
{
jenova::Error("Jenova Microsoft Compiler", "No GodotSDK Detected On Build System, Install At Least One From Package Manager!");
return false;
}
// Globalize Paths
selectedCompilerPath = ProjectSettings::get_singleton()->globalize_path(selectedCompilerPath);
selectedGodotKitPath = ProjectSettings::get_singleton()->globalize_path(selectedGodotKitPath);
// Solve Compiler Paths
this->projectPath = std::filesystem::absolute(AS_STD_STRING(projectPath)).string();
this->compilerBinaryPath = std::filesystem::absolute(AS_STD_STRING(selectedCompilerPath + String(compilerSettings["cpp_compiler_binary"]))).string();
this->linkerBinaryPath = std::filesystem::absolute(AS_STD_STRING(selectedCompilerPath + String(compilerSettings["cpp_linker_binary"]))).string();
this->includePath = std::filesystem::absolute(AS_STD_STRING(selectedCompilerPath + String(compilerSettings["cpp_include_path"]))).string();
this->libraryPath = std::filesystem::absolute(AS_STD_STRING(selectedCompilerPath + String(compilerSettings["cpp_library_path"]))).string();
this->jenovaSDKPath = std::filesystem::absolute(AS_STD_STRING(projectPath + String(compilerSettings["cpp_jenovasdk_path"]))).string();
this->godotSDKPath = std::filesystem::absolute(AS_STD_STRING(selectedGodotKitPath)).string();
this->jenovaCachePath = AS_STD_STRING(jenova::GetJenovaCacheDirectory());
// Store Solved Paths
this->internalDefaultSettings["compiler_solved_binary_path"] = String(this->compilerBinaryPath.c_str());
this->internalDefaultSettings["linker_solved_binary_path"] = String(this->linkerBinaryPath.c_str());
// All Good
return true;
}
private:
CompilerModel compilerModel = CompilerModel::Unspecified;
Dictionary internalDefaultSettings;
std::string projectPath;
std::string compilerBinaryPath;
std::string linkerBinaryPath;
std::string includePath;
std::string libraryPath;
std::string jenovaSDKPath;
std::string godotSDKPath;