-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathbuildimplementationcpp.go
More file actions
2457 lines (2111 loc) · 113 KB
/
buildimplementationcpp.go
File metadata and controls
2457 lines (2111 loc) · 113 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
/*++
Copyright (C) 2018 Autodesk Inc. (Original Author)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--*/
//////////////////////////////////////////////////////////////////////////////////////////////////////
// buildimplementationcpp.go
// functions to generate C++ interface classes, implementation stubs and wrapper code that maps to
// the C-header.
//////////////////////////////////////////////////////////////////////////////////////////////////////
package main
import (
"errors"
"fmt"
"log"
"path"
"strings"
)
// BuildImplementationCPP builds C++ interface classes, implementation stubs and wrapper code that maps to the C-header
func BuildImplementationCPP(component ComponentDefinition, outputFolder string, stubOutputFolder string, projectOutputFolder string, implementation ComponentDefinitionImplementation, suppressStub bool, suppressInterfaces bool) error {
forceRecreation := false
doJournal := len(component.Global.JournalMethod) > 0
NameSpace := component.NameSpace
ImplementationSubNameSpace := "Impl"
LibraryName := component.LibraryName
BaseName := component.BaseName
indentString := getIndentationString(implementation.Indentation)
stubIdentifier := ""
if len(implementation.StubIdentifier) > 0 {
stubIdentifier = "_" + strings.ToLower(implementation.StubIdentifier)
}
if !suppressInterfaces {
IntfExceptionHeaderName := path.Join(outputFolder, BaseName+"_interfaceexception.hpp")
log.Printf("Creating \"%s\"", IntfExceptionHeaderName)
hInternalExceptionHeaderFile, err := CreateLanguageFile(IntfExceptionHeaderName, indentString)
if err != nil {
return err
}
hInternalExceptionHeaderFile.WriteCLicenseHeader(component,
fmt.Sprintf("This is an autogenerated C++ Header file with the basic internal\n exception type in order to allow an easy use of %s", LibraryName),
true)
IntfExceptionImplName := path.Join(outputFolder, BaseName+"_interfaceexception.cpp")
log.Printf("Creating \"%s\"", IntfExceptionImplName)
hInternalExceptionImplFile, err := CreateLanguageFile(IntfExceptionImplName, indentString)
if err != nil {
return err
}
hInternalExceptionImplFile.WriteCLicenseHeader(component,
fmt.Sprintf("This is an autogenerated C++ Implementation file with the basic internal\n exception type in order to allow an easy use of %s", LibraryName),
true)
err = buildCPPInternalException(hInternalExceptionHeaderFile, hInternalExceptionImplFile, NameSpace, BaseName)
if err != nil {
return err
}
IntfHeaderName := path.Join(outputFolder, BaseName+"_interfaces.hpp")
log.Printf("Creating \"%s\"", IntfHeaderName)
interfaceshppfile, err := CreateLanguageFile(IntfHeaderName, indentString)
if err != nil {
return err
}
interfaceshppfile.WriteCLicenseHeader(component,
fmt.Sprintf("This is an autogenerated C++ header file in order to allow easy\ndevelopment of %s. The implementer of %s needs to\nderive concrete classes from the abstract classes in this header.", LibraryName, LibraryName),
true)
err = buildCPPInterfaces(component, interfaceshppfile, ImplementationSubNameSpace, implementation.ClassIdentifier)
if err != nil {
return err
}
IntfWrapperImplName := path.Join(outputFolder, BaseName+"_interfacewrapper.cpp")
log.Printf("Creating \"%s\"", IntfWrapperImplName)
cppWrapperfile, err := CreateLanguageFile(IntfWrapperImplName, indentString)
if err != nil {
return err
}
cppWrapperfile.WriteCLicenseHeader(component,
fmt.Sprintf("This is an autogenerated C++ implementation file in order to allow easy\ndevelopment of %s. The functions in this file need to be implemented. It needs to be generated only once.", LibraryName),
true)
err = buildCPPInterfaceWrapper(component, cppWrapperfile, NameSpace, ImplementationSubNameSpace, implementation.ClassIdentifier, BaseName, doJournal)
if err != nil {
return err
}
if doJournal {
IntfJournalHeaderName := path.Join(outputFolder, strings.ToLower(BaseName)+"_interfacejournal.hpp")
log.Printf("Creating \"%s\"", IntfJournalHeaderName)
interfacejournalhppfile, err := CreateLanguageFile(IntfJournalHeaderName, indentString)
if err != nil {
return err
}
interfacejournalhppfile.WriteCLicenseHeader(component,
fmt.Sprintf("This is an autogenerated C++ header file in order to allow easy\ndevelopment of %s. It provides an automatic Journaling mechanism for the library implementation.", LibraryName),
true)
IntfJournalImplName := path.Join(outputFolder, strings.ToLower(BaseName)+"_interfacejournal.cpp")
log.Printf("Creating \"%s\"", IntfJournalImplName)
interfacejournalcppfile, err := CreateLanguageFile(IntfJournalImplName, indentString)
if err != nil {
return err
}
interfacejournalcppfile.WriteCLicenseHeader(component,
fmt.Sprintf("This is an autogenerated C++ implementation file in order to allow easy\ndevelopment of %s. It provides an automatic Journaling mechanism for the library implementation.", LibraryName),
true)
err = buildJournalingCPP(component, interfacejournalhppfile, interfacejournalcppfile)
if err != nil {
return err
}
}
}
if !suppressStub {
err := buildCPPStub(component, NameSpace, ImplementationSubNameSpace, implementation.ClassIdentifier, BaseName, stubOutputFolder, indentString, stubIdentifier, forceRecreation)
if err != nil {
return err
}
IntfWrapperStubName := path.Join(stubOutputFolder, BaseName+stubIdentifier+".cpp")
if forceRecreation || (!FileExists(IntfWrapperStubName)) {
log.Printf("Creating \"%s\"", IntfWrapperStubName)
stubfile, err := CreateLanguageFile(IntfWrapperStubName, indentString)
if err != nil {
return err
}
stubfile.WriteCLicenseHeader(component,
fmt.Sprintf("This is an autogenerated C++ implementation file in order to allow easy\ndevelopment of %s. It needs to be generated only once.", LibraryName),
true)
err = buildCPPGlobalStubFile(component, stubfile, NameSpace, ImplementationSubNameSpace, implementation.ClassIdentifier, BaseName)
if err != nil {
return err
}
} else {
log.Printf("Omitting recreation of implementation stub \"%s\"", IntfWrapperStubName)
}
if len(projectOutputFolder) > 0 {
CMakeListsFileName := path.Join(projectOutputFolder, "CMakeLists.txt")
if forceRecreation || !FileExists(CMakeListsFileName) {
log.Printf("Creating CMake-Project \"%s\" for CPP Implementation", CMakeListsFileName)
CMakeListsFile, err := CreateLanguageFile(CMakeListsFileName, indentString)
if err != nil {
return err
}
CMakeListsFile.WriteCMakeLicenseHeader(component,
fmt.Sprintf("This is an autogenerated CMakeLists file for the development of %s.", LibraryName),
true)
buildCMakeForCPPImplementation(component, CMakeListsFile, doJournal)
} else {
log.Printf("Omitting recreation of CMake-Project \"%s\" for CPP Implementation", CMakeListsFileName)
}
}
}
return nil
}
func buildCPPInternalException(wHeader LanguageWriter, wImpl LanguageWriter, NameSpace string, BaseName string) error {
wHeader.Writeln("#ifndef __%s_INTERFACEEXCEPTION_HEADER", strings.ToUpper(NameSpace))
wHeader.Writeln("#define __%s_INTERFACEEXCEPTION_HEADER", strings.ToUpper(NameSpace))
wHeader.Writeln("")
wHeader.Writeln("#include <string>")
wHeader.Writeln("#include <exception>")
wHeader.Writeln("#include <stdexcept>")
wHeader.Writeln("#include \"%s_types.hpp\"", BaseName)
wHeader.Writeln("")
wHeader.Writeln("/*************************************************************************************************************************")
wHeader.Writeln(" Class E%sInterfaceException", NameSpace)
wHeader.Writeln("**************************************************************************************************************************/")
wHeader.Writeln("")
wHeader.Writeln("")
wHeader.Writeln("class E%sInterfaceException : public std::exception {", NameSpace)
wHeader.Writeln("protected:")
wHeader.Writeln(" /**")
wHeader.Writeln(" * Error code for the Exception.")
wHeader.Writeln(" */")
wHeader.Writeln(" %sResult m_errorCode;", NameSpace)
wHeader.Writeln(" /**")
wHeader.Writeln(" * Error message for the Exception.")
wHeader.Writeln(" */")
wHeader.Writeln(" std::string m_errorMessage;")
wHeader.Writeln("")
wHeader.Writeln("public:")
wHeader.Writeln(" /**")
wHeader.Writeln(" * Exception Constructor.")
wHeader.Writeln(" */")
wHeader.Writeln(" E%sInterfaceException(%sResult errorCode);", NameSpace, NameSpace)
wHeader.Writeln("")
wHeader.Writeln(" /**")
wHeader.Writeln(" * Custom Exception Constructor.")
wHeader.Writeln(" */")
wHeader.Writeln(" E%sInterfaceException(%sResult errorCode, std::string errorMessage);", NameSpace, NameSpace)
wHeader.Writeln("")
wHeader.Writeln(" /**")
wHeader.Writeln(" * Returns error code")
wHeader.Writeln(" */")
wHeader.Writeln(" %sResult getErrorCode();", NameSpace)
wHeader.Writeln(" /**")
wHeader.Writeln(" * Returns error message")
wHeader.Writeln(" */")
wHeader.Writeln(" const char* what() const noexcept override;")
wHeader.Writeln("};")
wHeader.Writeln("")
wHeader.Writeln("#endif // __%s_INTERFACEEXCEPTION_HEADER", strings.ToUpper(NameSpace))
wImpl.Writeln("")
wImpl.Writeln("#include <string>")
wImpl.Writeln("")
wImpl.Writeln("#include \"%s_interfaceexception.hpp\"", BaseName)
wImpl.Writeln("")
wImpl.Writeln("/*************************************************************************************************************************")
wImpl.Writeln(" Class E%sInterfaceException", NameSpace)
wImpl.Writeln("**************************************************************************************************************************/")
wImpl.Writeln("E%sInterfaceException::E%sInterfaceException(%sResult errorCode)", NameSpace, NameSpace, NameSpace)
wImpl.Writeln(" : m_errorMessage(%s_GETERRORSTRING (errorCode))", strings.ToUpper(NameSpace))
wImpl.Writeln("{")
wImpl.Writeln(" m_errorCode = errorCode;")
wImpl.Writeln("}")
wImpl.Writeln("")
wImpl.Writeln("E%sInterfaceException::E%sInterfaceException(%sResult errorCode, std::string errorMessage)", NameSpace, NameSpace, NameSpace)
wImpl.Writeln(" : m_errorMessage(errorMessage + \" (\" + std::to_string (errorCode) + \")\")")
wImpl.Writeln("{")
wImpl.Writeln(" m_errorCode = errorCode;")
wImpl.Writeln("}")
wImpl.Writeln("")
wImpl.Writeln("%sResult E%sInterfaceException::getErrorCode ()", NameSpace, NameSpace)
wImpl.Writeln("{")
wImpl.Writeln(" return m_errorCode;")
wImpl.Writeln("}")
wImpl.Writeln("")
wImpl.Writeln("const char * E%sInterfaceException::what () const noexcept", NameSpace)
wImpl.Writeln("{")
wImpl.Writeln(" return m_errorMessage.c_str();")
wImpl.Writeln("}")
wImpl.Writeln("")
return nil
}
func writeSharedPtrTemplate(component ComponentDefinition, w LanguageWriter, ClassIdentifier string) {
IBaseClassName := "I" + ClassIdentifier + component.Global.BaseClassName
w.Writeln("")
w.Writeln("")
w.Writeln("/**")
w.Writeln(" Definition of a shared pointer class for %s", IBaseClassName)
w.Writeln("*/")
IBaseSharedPtrName := "I" + component.Global.BaseClassName + "SharedPtr"
DeleteBaseMethodStr := ReleaseBaseClassInterfaceMethod(component.Global.BaseClassName).MethodName
w.Writeln("template<class T>")
w.Writeln("class %s : public std::shared_ptr<T>", IBaseSharedPtrName)
w.Writeln("{")
w.Writeln("public:")
w.Writeln(" explicit %s(T* t = nullptr)", IBaseSharedPtrName)
w.Writeln(" : std::shared_ptr<T>(t, %s::%s)", IBaseClassName, DeleteBaseMethodStr)
w.Writeln(" {")
w.Writeln(" t->%s();", IncRefCountMethod().MethodName)
w.Writeln(" }")
w.Writeln("")
w.Writeln(" // Reset function, as it also needs to properly set the deleter.")
w.Writeln(" void reset(T* t = nullptr)")
w.Writeln(" {")
w.Writeln(" std::shared_ptr<T>::reset(t, %s::%s);", IBaseClassName, DeleteBaseMethodStr)
w.Writeln(" }")
w.Writeln("")
w.Writeln(" // Get-function that increases the Base class's reference count")
w.Writeln(" T* getCoOwningPtr()")
w.Writeln(" {")
w.Writeln(" T* t = this->get();")
w.Writeln(" t->%s();", IncRefCountMethod().MethodName)
w.Writeln(" return t;")
w.Writeln(" }")
w.Writeln("};")
w.Writeln("")
}
func writeCPPClassInterface(component ComponentDefinition, class ComponentDefinitionClass, w LanguageWriter, NameSpace string, NameSpaceImplementation string, ClassIdentifier string, BaseName string) error {
w.Writeln("")
w.Writeln("/*************************************************************************************************************************")
w.Writeln(" Class interface for %s ", class.ClassName)
w.Writeln("**************************************************************************************************************************/")
w.Writeln("")
parentClassString := " "
if !component.isBaseClass(class) {
parentClassString = " : public virtual "
if class.ParentClass == "" {
parentClassString += fmt.Sprintf("I%s%s ", ClassIdentifier, component.Global.BaseClassName)
} else {
parentClassString += fmt.Sprintf("I%s%s ", ClassIdentifier, class.ParentClass)
}
}
classInterfaceName := fmt.Sprintf("I%s%s", ClassIdentifier, class.ClassName)
w.Writeln("class %s%s{", classInterfaceName, parentClassString)
if component.isStringOutBaseClass(class) {
w.Writeln("private:")
w.Writeln(" std::unique_ptr<ParameterCache> m_ParameterCache;")
}
w.Writeln("public:")
if component.isBaseClass(class) {
w.Writeln(" /**")
w.Writeln(" * %s::~%s - virtual destructor of %s", classInterfaceName, classInterfaceName, classInterfaceName)
w.Writeln(" */")
w.Writeln(" virtual ~%s() {};", classInterfaceName)
w.Writeln("")
releaseBaseClassInterfaceMethod := ReleaseBaseClassInterfaceMethod(component.Global.BaseClassName)
methodstring, _, err := buildCPPInterfaceMethodDeclaration(releaseBaseClassInterfaceMethod, class.ClassName, NameSpace, ClassIdentifier, BaseName, w.IndentString, true, false, true)
if err != nil {
return err
}
w.Writeln("%s", methodstring)
argument := "p" + releaseBaseClassInterfaceMethod.Params[0].ParamName
w.Writeln(" {")
w.Writeln(" if (%s) {", argument)
w.Writeln(" %s->%s();", argument, DecRefCountMethod().MethodName)
w.Writeln(" }")
w.Writeln(" };")
w.Writeln("")
acquireBaseClassInterfaceMethod := AcquireBaseClassInterfaceMethod(component.Global.BaseClassName)
methodstring, _, err = buildCPPInterfaceMethodDeclaration(acquireBaseClassInterfaceMethod, class.ClassName, NameSpace, ClassIdentifier, BaseName, w.IndentString, true, false, true)
if err != nil {
return err
}
w.Writeln("%s", methodstring)
argument = "p" + acquireBaseClassInterfaceMethod.Params[0].ParamName
w.Writeln(" {")
w.Writeln(" if (%s) {", argument)
w.Writeln(" %s->%s();", argument, IncRefCountMethod().MethodName)
w.Writeln(" }")
w.Writeln(" };")
w.Writeln("")
var methods [5]ComponentDefinitionMethod
methods[0] = GetLastErrorMessageMethod()
methods[1] = ClearErrorMessageMethod()
methods[2] = RegisterErrorMessageMethod()
methods[3] = IncRefCountMethod()
methods[4] = DecRefCountMethod()
for j := 0; j < len(methods); j++ {
methodstring, _, err := buildCPPInterfaceMethodDeclaration(methods[j], class.ClassName, NameSpace, ClassIdentifier, BaseName, w.IndentString, false, true, true)
if err != nil {
return err
}
w.Writeln("")
w.Writeln("%s;", methodstring)
}
}
if component.isStringOutBaseClass(class) {
w.Writeln("")
w.Writeln(" /**")
w.Writeln(" * %s::_setCache - set parameter cache of object", classInterfaceName)
w.Writeln(" */")
w.Writeln(" void _setCache(ParameterCache * pCache)")
w.Writeln(" {")
w.Writeln(" m_ParameterCache.reset(pCache);")
w.Writeln(" }")
w.Writeln("")
w.Writeln(" /**")
w.Writeln(" * %s::_getCache - returns parameter cache of object", classInterfaceName)
w.Writeln(" */")
w.Writeln(" ParameterCache* _getCache()")
w.Writeln(" {")
w.Writeln(" return m_ParameterCache.get();")
w.Writeln(" }")
w.Writeln("")
}
if component.isBaseClass(class) {
methodstring, _, err := buildCPPInterfaceMethodDeclaration(component.classTypeIdMethod(), class.ClassName, NameSpace, ClassIdentifier, BaseName, w.IndentString, false, true, true)
if err != nil {
return err
}
// Only IBase class has pure virtual ClassTypeId method. It's needed for proper interpretation of "override" in deriver interface classes.
w.Writeln("%s;", methodstring)
} else {
methodstring, _, err := buildCPPInterfaceMethodDeclaration(component.classTypeIdMethod(), class.ClassName, NameSpace, ClassIdentifier, BaseName, w.IndentString, false, false, true)
if err != nil {
return err
}
classTypeId, chashHashString := class.classTypeId(NameSpace)
w.Writeln("%s", methodstring)
w.Writeln(" {")
w.Writeln(" return 0x%XUL; // First 64 bits of SHA1 of a string: \"%s\"", classTypeId, chashHashString)
w.Writeln(" }")
w.Writeln("")
}
for j := 0; j < len(class.Methods); j++ {
method := class.Methods[j]
if method.MethodName == component.Global.ClassTypeIdMethod {
continue
}
methodstring, _, err := buildCPPInterfaceMethodDeclaration(method, class.ClassName, NameSpace, ClassIdentifier, BaseName, w.IndentString, false, true, true)
if err != nil {
return err
}
w.Writeln("%s;", methodstring)
w.Writeln("")
}
w.Writeln("};")
if component.isBaseClass(class) {
writeSharedPtrTemplate(component, w, ClassIdentifier)
}
w.Writeln("")
w.Writeln("typedef I%s%sSharedPtr<%s> P%s;", ClassIdentifier, component.Global.BaseClassName, classInterfaceName, classInterfaceName)
w.Writeln("")
return nil
}
func writeClassDefinitions(component ComponentDefinition, w LanguageWriter, NameSpaceImplementation string, ClassIdentifier string) {
NameSpace := component.NameSpace
BaseName := component.BaseName
for i := 0; i < len(component.Classes); i++ {
class := component.Classes[i]
writeCPPClassInterface(component, class, w, NameSpace, NameSpaceImplementation, ClassIdentifier, BaseName)
}
}
func writeParameterCacheDefinitions(component ComponentDefinition, w LanguageWriter, NameSpaceImplementation string, ClassIdentifier string) {
w.Writeln("")
w.Writeln("/*************************************************************************************************************************")
w.Writeln(" Parameter Cache definitions")
w.Writeln("**************************************************************************************************************************/")
w.Writeln("")
w.Writeln("class ParameterCache {")
w.Writeln(" public:")
w.Writeln(" virtual ~ParameterCache() {}")
w.Writeln("};")
w.Writeln("")
maxParamCount := component.countMaxOutParameters()
for paramCount := uint32(1); paramCount <= maxParamCount; paramCount++ {
classString := "class T1"
constructorString := "const T1 & param1"
assignmentString := "m_param1 (param1)"
retrieveString := "T1 & param1"
for paramIdx := uint32(2); paramIdx <= paramCount; paramIdx++ {
classString += fmt.Sprintf(", class T%d", paramIdx)
constructorString += fmt.Sprintf(", const T%d & param%d", paramIdx, paramIdx)
assignmentString += fmt.Sprintf(", m_param%d (param%d)", paramIdx, paramIdx)
retrieveString += fmt.Sprintf(", T%d & param%d", paramIdx, paramIdx)
}
w.Writeln("template <%s> class ParameterCache_%d : public ParameterCache {", classString, paramCount)
w.Writeln(" private:")
for paramIdx := uint32(1); paramIdx <= paramCount; paramIdx++ {
w.Writeln(" T%d m_param%d;", paramIdx, paramIdx)
}
w.Writeln(" public:")
w.Writeln(" ParameterCache_%d (%s)", paramCount, constructorString)
w.Writeln(" : %s", assignmentString)
w.Writeln(" {")
w.Writeln(" }")
w.Writeln("")
w.Writeln(" void retrieveData (%s)", retrieveString)
w.Writeln(" {")
for paramIdx := uint32(1); paramIdx <= paramCount; paramIdx++ {
w.Writeln(" param%d = m_param%d;", paramIdx, paramIdx)
}
w.Writeln(" }")
w.Writeln("};")
w.Writeln("")
}
}
func buildCPPInterfaces(component ComponentDefinition, w LanguageWriter, NameSpaceImplementation string, ClassIdentifier string) error {
NameSpace := component.NameSpace
BaseName := component.BaseName
w.Writeln("")
w.Writeln("#ifndef __%s_CPPINTERFACES", strings.ToUpper(NameSpace))
w.Writeln("#define __%s_CPPINTERFACES", strings.ToUpper(NameSpace))
w.Writeln("")
w.Writeln("#include <string>")
w.Writeln("#include <memory>")
w.Writeln("")
w.Writeln("#include \"%s_types.hpp\"", BaseName)
w.Writeln("")
w.Writeln("")
for _, subComponent := range component.ImportedComponentDefinitions {
w.Writeln("#include \"%s_dynamic.hpp\"", subComponent.BaseName)
}
w.Writeln("")
w.Writeln("namespace %s {", NameSpace)
w.Writeln("namespace %s {", NameSpaceImplementation)
w.Writeln("")
w.Writeln("/**")
w.Writeln(" Forward declarations of class interfaces")
w.Writeln("*/")
for i := 0; i < len(component.Classes); i++ {
class := component.Classes[i]
w.Writeln("class I%s%s;", ClassIdentifier, class.ClassName)
}
w.Writeln("")
w.Writeln("")
writeParameterCacheDefinitions(component, w, NameSpaceImplementation, ClassIdentifier)
writeClassDefinitions(component, w, NameSpaceImplementation, ClassIdentifier)
w.Writeln("")
w.Writeln("/*************************************************************************************************************************")
w.Writeln(" Global functions declarations")
w.Writeln("**************************************************************************************************************************/")
w.Writeln("class C%sWrapper {", ClassIdentifier)
w.Writeln("public:")
if len(component.ImportedComponentDefinitions) > 0 {
w.Writeln(" // Injected Components")
for _, subComponent := range component.ImportedComponentDefinitions {
subNameSpace := subComponent.NameSpace
w.Writeln(" static %s::PWrapper sP%sWrapper;", subNameSpace, subNameSpace)
}
w.Writeln("")
}
global := component.Global
for j := 0; j < len(global.Methods); j++ {
method := global.Methods[j]
// Omit special functions that are automatically implemented
isSpecialFunction, err := CheckHeaderSpecialFunction(method, global)
if err != nil {
return err
}
if (isSpecialFunction == eSpecialMethodJournal) || (isSpecialFunction == eSpecialMethodInjection) ||
(isSpecialFunction == eSpecialMethodSymbolLookup) {
continue
}
methodstring, _, err := buildCPPInterfaceMethodDeclaration(method, BaseName, NameSpace, ClassIdentifier, "Wrapper", w.IndentString, true, false, true)
if err != nil {
return err
}
w.Writeln("%s;", methodstring)
w.Writeln("")
}
w.Writeln("};")
w.Writeln("")
w.Writeln("%sResult %s_GetProcAddress (const char * pProcName, void ** ppProcAddress);", NameSpace, NameSpace)
w.Writeln("")
w.Writeln("} // namespace %s", NameSpaceImplementation)
w.Writeln("} // namespace %s", NameSpace)
w.Writeln("")
w.Writeln("#endif // __%s_CPPINTERFACES", strings.ToUpper(NameSpace))
return nil
}
func buildCPPGlobalStubFile(component ComponentDefinition, stubfile LanguageWriter, NameSpace string, NameSpaceImplementation string, ClassIdentifier string, BaseName string) error {
var defaultImplementation []string
defaultImplementation = append(defaultImplementation, fmt.Sprintf("throw E%sInterfaceException(%s_ERROR_NOTIMPLEMENTED);", NameSpace, strings.ToUpper(NameSpace)))
stubfile.Writeln("#include \"%s_abi.hpp\"", BaseName)
stubfile.Writeln("#include \"%s_interfaces.hpp\"", BaseName)
stubfile.Writeln("#include \"%s_interfaceexception.hpp\"", BaseName)
stubfile.Writeln("")
stubfile.Writeln("using namespace %s;", NameSpace)
stubfile.Writeln("using namespace %s::%s;", NameSpace, NameSpaceImplementation)
stubfile.Writeln("")
if len(component.ImportedComponentDefinitions) > 0 {
stubfile.Writeln("// Injected Components")
for _, subComponent := range component.ImportedComponentDefinitions {
subNameSpace := subComponent.NameSpace
stubfile.Writeln("%s::PWrapper C%sWrapper::sP%sWrapper;", subNameSpace, ClassIdentifier, subNameSpace)
}
stubfile.Writeln("")
}
for j := 0; j < len(component.Global.Methods); j++ {
method := component.Global.Methods[j]
thisMethodDefaultImpl := defaultImplementation
// Omit special functions that are automatically implemented
isSpecialFunction, err := CheckHeaderSpecialFunction(method, component.Global)
if err != nil {
return err
}
if (isSpecialFunction == eSpecialMethodJournal) || (isSpecialFunction == eSpecialMethodInjection) ||
(isSpecialFunction == eSpecialMethodSymbolLookup) {
continue
}
if isSpecialFunction == eSpecialMethodVersion {
var versionImplementation []string
versionImplementation = append(versionImplementation,
fmt.Sprintf("n%s = %s_VERSION_MAJOR;", method.Params[0].ParamName, strings.ToUpper(NameSpace)),
fmt.Sprintf("n%s = %s_VERSION_MINOR;", method.Params[1].ParamName, strings.ToUpper(NameSpace)),
fmt.Sprintf("n%s = %s_VERSION_MICRO;", method.Params[2].ParamName, strings.ToUpper(NameSpace)))
thisMethodDefaultImpl = versionImplementation
}
if isSpecialFunction == eSpecialMethodError {
var errorImplementation []string
errorImplementation = append(errorImplementation,
fmt.Sprintf("if (p%s) {", method.Params[0].ParamName),
fmt.Sprintf(" return p%s->%s (s%s);", method.Params[0].ParamName, GetLastErrorMessageMethod().MethodName, method.Params[1].ParamName),
"} else {",
" return false;",
"}")
thisMethodDefaultImpl = errorImplementation
}
if isSpecialFunction == eSpecialMethodRelease {
var releaseImplementation []string
releaseImplementation = append(releaseImplementation,
fmt.Sprintf("I%s%s::%s(p%s);", ClassIdentifier, component.Global.BaseClassName, ReleaseBaseClassInterfaceMethod(component.Global.BaseClassName).MethodName, method.Params[0].ParamName))
thisMethodDefaultImpl = releaseImplementation
}
if isSpecialFunction == eSpecialMethodAcquire {
var acquireImplementation []string
acquireImplementation = append(acquireImplementation,
fmt.Sprintf("I%s%s::%s(p%s);", ClassIdentifier, component.Global.BaseClassName, AcquireBaseClassInterfaceMethod(component.Global.BaseClassName).MethodName, method.Params[0].ParamName))
thisMethodDefaultImpl = acquireImplementation
}
_, implementationdeclaration, err := buildCPPInterfaceMethodDeclaration(method, "Wrapper", NameSpace, ClassIdentifier, BaseName, stubfile.IndentString, true, false, false)
if err != nil {
return err
}
stubfile.Writeln("%s", implementationdeclaration)
stubfile.Writeln("{")
stubfile.Writelns(" ", thisMethodDefaultImpl)
stubfile.Writeln("}")
stubfile.Writeln("")
}
stubfile.Writeln("")
return nil
}
func buildCPPInterfaceWrapperMethods(component ComponentDefinition, class ComponentDefinitionClass, w LanguageWriter, NameSpace string, NameSpaceImplementation string, ClassIdentifier string, BaseName string, doJournal bool) error {
w.Writeln("")
w.Writeln("/*************************************************************************************************************************")
w.Writeln(" Class implementation for %s", class.ClassName)
w.Writeln("**************************************************************************************************************************/")
for j := 0; j < len(class.Methods); j++ {
method := class.Methods[j]
err := writeCImplementationMethod(component, method, w, BaseName, NameSpace, NameSpaceImplementation, ClassIdentifier, class.ClassName, component.Global.BaseClassName, false, doJournal, eSpecialMethodNone, component.isStringOutClass(class))
if err != nil {
return err
}
}
return nil
}
func buildCPPGetSymbolAddressMethod(component ComponentDefinition, w LanguageWriter, NameSpace string, NameSpaceImplementation string) error {
w.Writeln("")
w.Writeln("/*************************************************************************************************************************")
w.Writeln(" Function table lookup implementation")
w.Writeln("**************************************************************************************************************************/")
w.Writeln("")
w.Writeln("%sResult %s::%s::%s_GetProcAddress (const char * pProcName, void ** ppProcAddress)", NameSpace, NameSpace, NameSpaceImplementation, NameSpace)
w.Writeln("{")
w.AddIndentationLevel(1)
var processfuncMap []string
global := component.Global
for i := 0; i < len(component.Classes); i++ {
class := component.Classes[i]
for j := 0; j < len(class.Methods); j++ {
method := class.Methods[j]
procName := strings.ToLower(class.ClassName + "_" + method.MethodName)
processfuncMap = append(processfuncMap, fmt.Sprintf("%s_%s", strings.ToLower(NameSpace), procName))
}
}
for j := 0; j < len(global.Methods); j++ {
method := global.Methods[j]
procName := strings.ToLower(method.MethodName)
processfuncMap = append(processfuncMap, fmt.Sprintf("%s_%s", strings.ToLower(NameSpace), procName))
}
w.Writeln("if (pProcName == nullptr)")
w.Writeln(" return %s_ERROR_INVALIDPARAM;", strings.ToUpper(NameSpace))
w.Writeln("if (ppProcAddress == nullptr)")
w.Writeln(" return %s_ERROR_INVALIDPARAM;", strings.ToUpper(NameSpace))
w.Writeln("*ppProcAddress = nullptr;")
w.Writeln("std::string sProcName (pProcName);")
w.Writeln("")
for j := 0; j < len(processfuncMap); j++ {
w.Writeln("if (sProcName == \"%s\") ", processfuncMap[j])
w.Writeln(" *ppProcAddress = (void*) &%s;", processfuncMap[j])
}
w.Writeln("")
w.Writeln("if (*ppProcAddress == nullptr) ")
w.Writeln(" return %s_ERROR_COULDNOTFINDLIBRARYEXPORT;", strings.ToUpper(NameSpace))
w.Writeln("return %s_SUCCESS;", strings.ToUpper(NameSpace))
w.AddIndentationLevel(-1)
w.Writeln("}")
return nil
}
func buildCPPInterfaceWrapper(component ComponentDefinition, w LanguageWriter, NameSpace string, NameSpaceImplementation string, ClassIdentifier string, BaseName string, doJournal bool) error {
w.Writeln("#include \"%s_abi.hpp\"", strings.ToLower(BaseName))
w.Writeln("#include \"%s_interfaces.hpp\"", strings.ToLower(BaseName))
w.Writeln("#include \"%s_interfaceexception.hpp\"", strings.ToLower(BaseName))
if doJournal {
w.Writeln("#include \"%s_interfacejournal.hpp\"", strings.ToLower(BaseName))
}
w.Writeln("")
w.Writeln("#include <map>")
w.Writeln("")
w.Writeln("using namespace %s::%s;", NameSpace, NameSpaceImplementation)
w.Writeln("")
if doJournal {
w.Writeln("P%sInterfaceJournal m_GlobalJournal;", NameSpace)
w.Writeln("")
}
journalParameter := ""
if doJournal {
journalParameter = fmt.Sprintf(", C%sInterfaceJournalEntry * pJournalEntry = nullptr", NameSpace)
}
IBaseClassName := "I" + ClassIdentifier + component.Global.BaseClassName
registerErrorMethod := RegisterErrorMessageMethod()
w.Writeln("%sResult handle%sException(%s * pIBaseClass, E%sInterfaceException & Exception%s)", NameSpace, NameSpace, IBaseClassName, NameSpace, journalParameter)
w.Writeln("{")
w.Writeln(" %sResult errorCode = Exception.getErrorCode();", NameSpace)
w.Writeln("")
if doJournal {
w.Writeln(" if (pJournalEntry != nullptr)")
w.Writeln(" pJournalEntry->writeError(errorCode);")
w.Writeln("")
}
w.Writeln(" if (pIBaseClass != nullptr)")
w.Writeln(" pIBaseClass->%s(Exception.what());", registerErrorMethod.MethodName)
w.Writeln("")
w.Writeln(" return errorCode;")
w.Writeln("}")
w.Writeln("")
w.Writeln("%sResult handleStdException(%s * pIBaseClass, std::exception & Exception%s)", NameSpace, IBaseClassName, journalParameter)
w.Writeln("{")
w.Writeln(" %sResult errorCode = %s_ERROR_GENERICEXCEPTION;", NameSpace, strings.ToUpper(NameSpace))
w.Writeln("")
if doJournal {
w.Writeln(" if (pJournalEntry != nullptr)")
w.Writeln(" pJournalEntry->writeError(errorCode);")
w.Writeln("")
}
w.Writeln(" if (pIBaseClass != nullptr)")
w.Writeln(" pIBaseClass->%s(Exception.what());", registerErrorMethod.MethodName)
w.Writeln("")
w.Writeln(" return errorCode;")
w.Writeln("}")
w.Writeln("")
w.Writeln("%sResult handleUnhandledException(%s * pIBaseClass%s)", NameSpace, IBaseClassName, journalParameter)
w.Writeln("{")
w.Writeln(" %sResult errorCode = %s_ERROR_GENERICEXCEPTION;", NameSpace, strings.ToUpper(NameSpace))
w.Writeln("")
if doJournal {
w.Writeln(" if (pJournalEntry != nullptr)")
w.Writeln(" pJournalEntry->writeError(errorCode);")
w.Writeln("")
}
w.Writeln(" if (pIBaseClass != nullptr)")
w.Writeln(" pIBaseClass->%s(\"Unhandled Exception\");", registerErrorMethod.MethodName)
w.Writeln("")
w.Writeln(" return errorCode;")
w.Writeln("}")
w.Writeln("")
w.Writeln("")
for i := 0; i < len(component.Classes); i++ {
class := component.Classes[i]
err := buildCPPInterfaceWrapperMethods(component, class, w, NameSpace, NameSpaceImplementation, ClassIdentifier, BaseName, doJournal)
if err != nil {
return err
}
}
w.Writeln("")
err := buildCPPGetSymbolAddressMethod(component, w, NameSpace, NameSpaceImplementation)
if err != nil {
return err
}
w.Writeln("")
w.Writeln("/*************************************************************************************************************************")
w.Writeln(" Global functions implementation")
w.Writeln("**************************************************************************************************************************/")
global := component.Global
for j := 0; j < len(global.Methods); j++ {
method := global.Methods[j]
// Check for special functions
isSpecialFunction, err := CheckHeaderSpecialFunction(method, global)
if err != nil {
return err
}
// Do not self-journal Journal special method
doMethodJournal := doJournal
if isSpecialFunction == eSpecialMethodJournal {
doMethodJournal = false
}
// Write Static function implementation
err = writeCImplementationMethod(component, method, w, BaseName, NameSpace, NameSpaceImplementation, ClassIdentifier, "Wrapper", component.Global.BaseClassName, true, doMethodJournal, isSpecialFunction, false)
if err != nil {
return err
}
}
w.Writeln("")
return nil
}
func buildOutCacheTemplateParameters(method ComponentDefinitionMethod, NameSpace string, BaseClassName string, ClassIdentifier string) (string, error) {
result := ""
for i := 0; i < len(method.Params); i++ {
param := method.Params[i]
if (param.ParamPass == "out") || (param.ParamPass == "return") {
if result != "" {
result += ", "
}
cppParamType := getCppParamType(param, NameSpace, true)
if param.ParamType == "class" || param.ParamType == "optionalclass" {
cppParamType = fmt.Sprintf("I%s%s*", ClassIdentifier, param.ParamClass)
}
result += cppParamType
}
}
return result, nil
}
func writeCImplementationMethod(component ComponentDefinition, method ComponentDefinitionMethod, w LanguageWriter, BaseName string, NameSpace string, NameSpaceImplementation string, ClassIdentifier string, ClassName string, BaseClassName string, isGlobal bool, doJournal bool, isSpecialFunction int, isStringOutClass bool) error {
CMethodName := ""
cParams, err := GenerateCParameters(method, ClassName, NameSpace)
if err != nil {
return err
}
cparameters := ""
for _, cParam := range cParams {
if cparameters != "" {
cparameters = cparameters + ", "
}
cparameters = cparameters + cParam.ParamType + " " + cParam.ParamName
}
if isGlobal {
CMethodName = fmt.Sprintf("%s_%s", strings.ToLower(NameSpace), strings.ToLower(method.MethodName))
} else {
CMethodName = fmt.Sprintf("%s_%s_%s", strings.ToLower(NameSpace), strings.ToLower(ClassName), strings.ToLower(method.MethodName))
if cparameters != "" {
cparameters = ", " + cparameters
}
cparameters = fmt.Sprintf("%s_%s p%s", NameSpace, ClassName, ClassName) + cparameters
}
callCPPFunctionCode := make([]string, 0)
checkInputCPPFunctionCode, preCallCPPFunctionCode, postCallCPPFunctionCode, returnVariable, callParameters, outCallParameters, err := generatePrePostCallCPPFunctionCode(component, method, NameSpace, ClassIdentifier, ClassName, BaseClassName)
if err != nil {
return err
}
if isSpecialFunction == eSpecialMethodJournal {
callCPPFunctionCode = append(callCPPFunctionCode, "m_GlobalJournal = nullptr;")
callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf("if (s%s != \"\") {", method.Params[0].ParamName))
callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" m_GlobalJournal = std::make_shared<C%sInterfaceJournal> (s%s);", NameSpace, method.Params[0].ParamName))
callCPPFunctionCode = append(callCPPFunctionCode, "}")
} else if isSpecialFunction == eSpecialMethodInjection {
callCPPFunctionCode = append(callCPPFunctionCode, "")
callCPPFunctionCode = append(callCPPFunctionCode, "bool bNameSpaceFound = false;")
callCPPFunctionCode = append(callCPPFunctionCode, "")
for _, subComponent := range component.ImportedComponentDefinitions {
theNameSpace := subComponent.NameSpace
callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf("if (s%s == \"%s\") {", method.Params[0].ParamName, theNameSpace))
wrapperName := "C" + ClassIdentifier + "Wrapper"
callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" if (%s::sP%sWrapper.get() != nullptr) {", wrapperName, theNameSpace))
callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" throw E%sInterfaceException(%s_ERROR_COULDNOTLOADLIBRARY);", NameSpace, strings.ToUpper(NameSpace)))
callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" }"))
callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" %s::sP%sWrapper = %s::CWrapper::loadLibraryFromSymbolLookupMethod(p%s);", wrapperName, theNameSpace, theNameSpace, method.Params[1].ParamName))
callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" bNameSpaceFound = true;"))
callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf("}"))
}
callCPPFunctionCode = append(callCPPFunctionCode, "")
callCPPFunctionCode = append(callCPPFunctionCode, "if (!bNameSpaceFound)")
callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" throw E%sInterfaceException(%s_ERROR_COULDNOTLOADLIBRARY);", NameSpace, strings.ToUpper(NameSpace)))
callCPPFunctionCode = append(callCPPFunctionCode, "")
} else if isSpecialFunction == eSpecialMethodSymbolLookup {
callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf("*p%s = (void*)&%s::%s::%s_GetProcAddress;", method.Params[0].ParamName, NameSpace, NameSpaceImplementation, NameSpace))
} else {
callCode, err := generateCallCPPFunctionCode(method, NameSpace, ClassIdentifier, ClassName, returnVariable, callParameters, isGlobal)
if err != nil {
return err
}
stringOutParameters := method.getStringOutParameters()
outParameterCount := method.countOutParameters()
// Special functions are an exception for string outs in global functions!
bHasCacheCall := (len(stringOutParameters) > 0) && (isSpecialFunction != eSpecialMethodError) && (isSpecialFunction != eSpecialMethodBuildinfo) && (isSpecialFunction != eSpecialMethodPrerelease)
if method.DisableStringOutCache {
bHasCacheCall = false
}
if bHasCacheCall {
if isGlobal {
return errors.New("String out parameter not allowed in global functions: " + method.MethodName)
}
if !isStringOutClass {
return errors.New("String out parameter without being the string out base class: " + method.MethodName)
}