-
Notifications
You must be signed in to change notification settings - Fork 252
Expand file tree
/
Copy pathGenerator.cpp
More file actions
894 lines (788 loc) · 29.1 KB
/
Generator.cpp
File metadata and controls
894 lines (788 loc) · 29.1 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
/*
* Copyright (c) 2014-2015, Freescale Semiconductor, Inc.
* Copyright 2016-2023 NXP
* All rights reserved.
*
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "Generator.hpp"
#include "erpc_version.h"
#include "Logging.hpp"
#include "ParseErrors.hpp"
#include "annotations.h"
#include "format_string.hpp"
#include <algorithm>
#include <cstring>
#include <ctime>
#include <filesystem>
#include <list>
using namespace erpcgen;
using namespace cpptempl;
using namespace std;
////////////////////////////////////////////////////////////////////////////////
// Code
////////////////////////////////////////////////////////////////////////////////
Generator::Generator(InterfaceDefinition *def, generator_type_t generatorType) :
m_idlCrc16(def->getIdlCrc16()), m_def(def), m_globals(&(def->getGlobals())), m_generatorType(generatorType)
{
string scopeName = "erpcShim";
string scopeNameC;
string scopeNamePrefix = "";
string namespaceVal = scopeName;
m_templateData["erpcVersion"] = ERPC_VERSION;
m_templateData["erpcVersionNumber"] = ERPC_VERSION_NUMBER;
// crc of erpcgen version and idl files.
m_templateData["crc16"] = "";
m_templateData["todaysDate"] = getTime();
m_templateData["sharedMemBeginAddr"] = "";
m_templateData["sharedMemEndAddr"] = "";
m_outputDirectory = m_def->getOutputDirectory();
if (m_def->hasProgramSymbol())
{
Log::info("program: ");
Log::info("%s\n", m_def->getOutputFilename().c_str());
Program *program = m_def->getProgramSymbol();
/* Shared memory area. */
Value *sharedMemBValue = getAnnValue(program, SHARED_MEMORY_BEGIN_ANNOTATION);
Value *sharedMemEValue = getAnnValue(program, SHARED_MEMORY_END_ANNOTATION);
if (sharedMemBValue && sharedMemEValue)
{
m_templateData["sharedMemBeginAddr"] = sharedMemBValue->toString();
m_templateData["sharedMemEndAddr"] = sharedMemEValue->toString();
Log::warning("Shared memory is supported only for C language used on embedded devices.\n");
}
else if (sharedMemBValue || sharedMemEValue)
{
throw semantic_error(
"Annotations @shared_memory_begin and @shared_memory_end both (or no one) need exists and contains "
"addresses.");
}
if (findAnnotation(program, CRC_ANNOTATION) != nullptr)
{
m_templateData["crc16"] = m_idlCrc16;
}
m_outputDirectory /= getAnnStringValue(program, OUTPUT_DIR_ANNOTATION);
if (findAnnotation(program, SCOPE_NAME_ANNOTATION) == nullptr)
{
scopeName = program->getName();
}
else
{
scopeName = getAnnStringValue(program, SCOPE_NAME_ANNOTATION);
}
if (findAnnotation(program, NAMESPACE_ANNOTATION) != nullptr)
{
namespaceVal = getAnnStringValue(program, NAMESPACE_ANNOTATION);
}
}
m_templateData["scopeName"] = scopeName;
if (scopeName != "")
{
scopeNameC = scopeName;
std::transform(scopeNameC.begin(), scopeNameC.end(), scopeNameC.begin(), ::toupper);
scopeNamePrefix = "_";
}
m_templateData["scopeNameC"] = scopeNameC;
m_templateData["scopeNamePrefix"] = scopeNamePrefix;
m_templateData["namespace"] = namespaceVal;
// get group annotation with vector of theirs interfaces
m_groups.clear();
data_list groupNames;
Group *defaultGroup = new Group("");
for (auto it : m_globals->getSymbolsOfType(Symbol::symbol_type_t::kInterfaceSymbol))
{
Interface *iface = dynamic_cast<Interface *>(it);
assert(iface);
// interface has group annotation
vector<Annotation *> groupAnns = getAnnotations(iface, GROUP_ANNOTATION);
if (!groupAnns.empty())
{
for (auto groupAnnIt : groupAnns)
{
string name = (groupAnnIt->hasValue()) ? groupAnnIt->getValueObject()->toString() : "";
Group *group = getGroupByName(name);
if (group == nullptr)
{
group = new Group(name);
m_groups.push_back(group);
groupNames.push_back(name);
}
group->addInterface(iface);
}
}
else
{
// interface belongs to default group
defaultGroup->addInterface(iface);
}
}
// add default group only if it has any interface or there is no other group
if (defaultGroup->getInterfaces().size() > 0 || m_groups.size() == 0)
{
m_groups.push_back(defaultGroup);
}
Log::debug("Groups:\n");
for (Group *group : m_groups)
{
Log::log(" %s\n", group->getDescription().c_str());
}
// list of group names (used for including group header files for callbacks)
m_templateData["groupNames"] = groupNames;
// set codec information
switch (m_def->getCodecType())
{
case InterfaceDefinition::codec_t::kBasicCodec:
{
m_templateData["codecClass"] = "BasicCodec";
m_templateData["codecHeader"] = "erpc_basic_codec.hpp";
break;
}
default:
{
m_templateData["codecClass"] = "Codec";
m_templateData["codecHeader"] = "erpc_codec.hpp";
break;
}
}
}
Group *Generator::getGroupByName(const string &name)
{
for (Group *group : m_groups)
{
if (group->getName() == name)
{
return group;
}
}
return nullptr;
}
void Generator::openFile(ofstream &fileOutputStream, const string &fileName)
{
if (!m_outputDirectory.empty())
{
// TODO: do we have to create a copy of the outputDir here? Doesn't make sense...
std::filesystem::create_directories(m_outputDirectory);
if (!std::filesystem::is_directory(m_outputDirectory))
{
throw runtime_error(format_string("could not create directory path '%s'", m_outputDirectory.c_str()));
}
}
string filePathWithName = (m_outputDirectory / fileName).string();
// Open file.
fileOutputStream.open(filePathWithName, ios::out | ios::binary);
if (!fileOutputStream.is_open())
{
throw runtime_error(format_string("could not open output file '%s'", filePathWithName.c_str()));
}
}
void Generator::generateOutputFile(const string &fileName, const string &templateName, data_map &templateData,
const char *const kParseFile)
{
ofstream fileOutputStream;
openFile(fileOutputStream, fileName);
// Run template and write output to output files. Catch and rethrow template exceptions
// so we can add the name of the template that caused the error to aid in debugging.
try
{
parse(fileOutputStream, kParseFile, templateData);
fileOutputStream.close();
}
catch (TemplateException &e)
{
throw TemplateException(format_string("Template %s: %s", templateName.c_str(), e.what()));
}
}
string Generator::stripExtension(const string &filename)
{
auto result = filename.rfind('.');
if (result != string::npos)
{
return filename.substr(0, result);
}
else
{
return filename;
}
}
StructMember *Generator::findParamReferencedFromAnn(const StructType::member_vector_t &members,
const string &referenceName, const string &annName)
{
for (StructMember *structMember : members)
{
string lengthName = getAnnStringValue(structMember, annName);
if (strcmp(lengthName.c_str(), referenceName.c_str()) == 0)
{
return structMember;
}
}
return nullptr;
}
StructMember *Generator::findParamReferencedFromUnion(const StructType::member_vector_t &members,
const string &referenceName)
{
for (StructMember *structMember : members)
{
DataType *trueDataType = structMember->getDataType()->getTrueDataType();
if (trueDataType->isUnion())
{
UnionType *unionType = dynamic_cast<UnionType *>(trueDataType);
assert(unionType);
if (unionType->isNonEncapsulatedUnion())
{
string lengthName = getAnnStringValue(structMember, DISCRIMINATOR_ANNOTATION);
if (strcmp(lengthName.c_str(), referenceName.c_str()) == 0)
{
return structMember;
}
}
else
{
if (strcmp(unionType->getDiscriminatorName().c_str(), referenceName.c_str()) == 0)
{
return structMember;
}
}
}
}
return nullptr;
}
StructMember *Generator::findParamReferencedFrom(const StructType::member_vector_t &members,
const string &referenceName)
{
StructMember *referencedFrom = findParamReferencedFromAnn(members, referenceName, LENGTH_ANNOTATION);
if (referencedFrom)
{
return referencedFrom;
}
else
{
return findParamReferencedFromUnion(members, referenceName);
}
}
string Generator::getTime()
{
time_t now = time(nullptr);
string nowString = ctime(&now);
nowString.pop_back(); // Remove trailing newline.
return nowString;
}
DataType *Generator::findChildDataType(set<DataType *> &dataTypes, DataType *dataType)
{
// Detecting loops from forward declarations.
// Insert data type into set
if (!dataTypes.insert(dataType).second)
{
return dataType;
}
switch (dataType->getDataType())
{
case DataType::data_type_t::kAliasType:
{
AliasType *aliasType = dynamic_cast<AliasType *>(dataType);
if (aliasType != nullptr)
{
findChildDataType(dataTypes, aliasType->getElementType());
}
break;
}
case DataType::data_type_t::kArrayType:
{
ArrayType *arrayType = dynamic_cast<ArrayType *>(dataType);
if (arrayType != nullptr)
{
findChildDataType(dataTypes, arrayType->getElementType());
}
break;
}
case DataType::data_type_t::kListType:
{
ListType *listType = dynamic_cast<ListType *>(dataType);
if (listType != nullptr)
{
findChildDataType(dataTypes, listType->getElementType());
}
break;
}
case DataType::data_type_t::kStructType:
{
StructType *structType = dynamic_cast<StructType *>(dataType);
if (structType != nullptr)
{
for (StructMember *structMember : structType->getMembers())
{
findChildDataType(dataTypes, structMember->getDataType());
}
}
break;
}
case DataType::data_type_t::kUnionType:
{
// Keil need extra pragma option when unions are used.
m_templateData["usedUnionType"] = true;
UnionType *unionType = dynamic_cast<UnionType *>(dataType);
if (unionType != nullptr)
{
for (auto unionMember : unionType->getUnionMembers().getMembers())
{
findChildDataType(dataTypes, unionMember->getDataType());
}
}
break;
}
default:
{
break;
}
}
return dataType;
}
void Generator::findGroupDataTypes()
{
for (Group *group : m_groups)
{
for (Interface *iface : group->getInterfaces())
{
for (Function *fn : iface->getFunctions())
{
// handle return value
set<DataType *> dataTypes;
StructMember *structMember = fn->getReturnStructMemberType();
DataType *transformedDataType = findChildDataType(dataTypes, fn->getReturnType());
structMember->setDataType(transformedDataType);
// save all transformed data types directions into data type map
if (!findAnnotation(fn->getReturnType(), SHARED_ANNOTATION))
{
for (DataType *dataType : dataTypes)
{
group->addDirToSymbolsMap(dataType, param_direction_t::kReturn);
}
}
// handle function parameters
auto params = fn->getParameters().getMembers();
for (auto mit : params)
{
dataTypes.clear();
setBinaryList(mit);
mit->setDataType(findChildDataType(dataTypes, mit->getDataType()));
// save all transformed data types directions into data type map
if (!findAnnotation(mit, SHARED_ANNOTATION))
{
for (DataType *dataType : dataTypes)
{
group->addDirToSymbolsMap(dataType, mit->getDirection());
}
}
}
}
}
}
}
data_list Generator::makeGroupInterfacesTemplateData(Group *group)
{
Log::info("interfaces:\n");
data_list interfaces;
int n = 0;
for (Interface *iface : group->getInterfaces())
{
data_map ifaceInfo;
ifaceInfo["name"] = make_data(getOutputName(iface));
ifaceInfo["id"] = data_ptr(iface->getUniqueId());
setTemplateComments(iface, ifaceInfo);
// TODO: for C only?
ifaceInfo["serviceClassName"] = getOutputName(iface) + "_service";
ifaceInfo["clientClassName"] = getOutputName(iface) + "_client";
ifaceInfo["serverClassName"] = getOutputName(iface) + "_server";
ifaceInfo["interfaceClassName"] = getOutputName(iface) + "_interface";
Log::info("%d: (%d) %s\n", n++, iface->getUniqueId(), iface->getName().c_str());
/* Has interface function declared as non-external? */
data_list functions = getFunctionsTemplateData(group, iface);
ifaceInfo["functions"] = functions;
data_list callbacksInt;
data_list callbacksExt;
data_list callbacksAll;
getCallbacksTemplateData(group, iface, callbacksInt, callbacksExt, callbacksAll);
ifaceInfo["callbacksInt"] = callbacksInt;
ifaceInfo["callbacksAll"] = callbacksAll;
ifaceInfo["isNonExternalInterface"] = false;
for (unsigned int i = 0; i < functions.size(); ++i)
{
assert(dynamic_cast<DataMap *>(functions[i].get().get()));
string isNonExternalFunction =
dynamic_cast<DataMap *>(functions[i].get().get())->getmap()["isNonExternalFunction"]->getvalue();
if (isNonExternalFunction.compare("true") == 0)
{
ifaceInfo["isNonExternalInterface"] = true;
break;
}
}
// Generate compile-time hash table for this interface
data_map hashTableInfo = generateHashTableData(iface, functions);
ifaceInfo["hashTable"] = hashTableInfo;
interfaces.push_back(ifaceInfo);
}
return interfaces;
}
string Generator::getGroupCommonFileName(Group *group)
{
string fileName = "";
if (!group->getInterfaces().empty() || (m_groups.size() == 1 && group->getName() == ""))
{
string groupName = group->getName();
fileName = stripExtension(m_def->getOutputFilename());
m_templateData["outputFilename"] = fileName;
if (groupName != "")
{
fileName += "_" + groupName;
}
Log::info("File name %s\n", fileName.c_str());
}
return fileName;
}
void Generator::generateGroupOutputFiles(Group *group)
{
// generate output files only for groups with interfaces or for IDLs with no interfaces at all
if (!group->getInterfaces().empty() || (m_groups.size() == 1 && group->getName() == ""))
{
string fileName = getGroupCommonFileName(group);
// group templates
m_templateData["group"] = group->getTemplate();
// Log template data.
if (Log::getLogger()->getFilterLevel() >= Logger::log_level_t::kDebug2)
{
dump_data(m_templateData);
}
generateOutputFiles(fileName);
}
}
void Generator::makeIncludesTemplateData()
{
data_list includeData;
if (m_def->hasProgramSymbol())
{
for (auto include : getAnnotations(m_def->getProgramSymbol(), INCLUDE_ANNOTATION))
{
includeData.push_back(make_data(include->getValueObject()->toString()));
Log::info("include %s\n", include->getValueObject()->toString().c_str());
}
}
m_templateData["includes"] = includeData;
}
data_list Generator::makeGroupIncludesTemplateData(Group *group)
{
data_list includes;
set<string> tempSet;
for (Interface *iface : group->getInterfaces())
{
Annotation *includeAnn = findAnnotation(iface, INCLUDE_ANNOTATION);
if (includeAnn)
{
string include = includeAnn->getValueObject()->toString();
if (tempSet.find(include) == tempSet.end())
{
includes.push_back(include);
tempSet.insert(include);
}
}
for (Function *func : iface->getFunctions())
{
Annotation *funcAnn = findAnnotation(func, INCLUDE_ANNOTATION);
if (funcAnn)
{
string include = funcAnn->getValueObject()->toString();
if (tempSet.find(include) == tempSet.end())
{
includes.push_back(include);
tempSet.insert(include);
}
}
}
}
return includes;
}
bool Generator::isMemberDataTypeUsingForwardDeclaration(Symbol *topSymbol, Symbol *memberSymbol)
{
return (m_globals->getSymbolPos(topSymbol) < m_globals->getSymbolPos(memberSymbol));
}
string Generator::getOutputName(Symbol *symbol, bool check)
{
string annName;
uint32_t line;
Annotation *ann = findAnnotation(symbol, NAME_ANNOTATION);
if (ann)
{
annName = ann->getValueObject()->toString();
if (annName.empty())
{
throw semantic_error(format_string("Missing value for annotation named @%s on line '%d'", NAME_ANNOTATION,
ann->getLocation().m_firstLine));
}
Log::warning(
"line %d: Be careful when @%s annotation is used. This can cause compile issue. See documentation.\n",
ann->getLocation().m_firstLine, NAME_ANNOTATION);
line = ann->getLocation().m_firstLine;
}
else
{
annName = symbol->getName();
line = symbol->getFirstLine();
}
if (check)
{
auto it = reserverdWords.find(annName);
if (it != reserverdWords.end())
{
throw semantic_error(format_string(
"line %d: Wrong symbol name '%s'. Cannot use program language reserved words.", line, annName.c_str()));
}
}
return annName;
}
Annotation::program_lang_t Generator::getAnnotationLang()
{
if (m_generatorType == generator_type_t::kC)
{
return Annotation::program_lang_t::kC;
}
else if (m_generatorType == generator_type_t::kPython)
{
return Annotation::program_lang_t::kPython;
}
else if (m_generatorType == generator_type_t::kJava)
{
return Annotation::program_lang_t::kJava;
}
throw internal_error("Unsupported generator type specified for annotation.");
}
Annotation *Generator::findAnnotation(Symbol *symbol, const string &name)
{
return symbol->findAnnotation(name, getAnnotationLang());
}
vector<Annotation *> Generator::getAnnotations(Symbol *symbol, const string &name)
{
return symbol->getAnnotations(name, getAnnotationLang());
}
Value *Generator::getAnnValue(Symbol *symbol, const string &name)
{
return symbol->getAnnValue(name, getAnnotationLang());
}
string Generator::getAnnStringValue(Symbol *symbol, const string &name)
{
return symbol->getAnnStringValue(name, getAnnotationLang());
}
data_list Generator::getFunctionsTemplateData(Group *group, Interface *iface)
{
data_list fns;
int j = 0;
for (auto fit : iface->getFunctions())
{
data_map function = getFunctionTemplateData(group, fit);
fns.push_back(function);
Log::info(" %d: (%d) %s\n", j, fit->getUniqueId(), function["prototype"]->getvalue().c_str());
}
return fns;
}
Generator::datatype_vector_t Generator::getDataTypesFromSymbolScope(SymbolScope *scope, DataType::data_type_t datatype)
{
datatype_vector_t vector;
for (Symbol *symbol : scope->getSymbolsOfType(Symbol::symbol_type_t::kTypenameSymbol))
{
DataType *dataType = dynamic_cast<DataType *>(symbol);
if (dataType->getDataType() == datatype)
{
vector.push_back(dataType);
}
}
return vector;
}
void Generator::getCallbacksTemplateData(Group *group, const Interface *iface, data_list &callbackTypesInt,
data_list &callbackTypesExt, data_list &callbackTypesAll)
{
list<FunctionType *> callbackTypes;
list<string> interfacesNames;
list<string> callbackTypesNames;
interfacesNames.push_back(iface->getName());
for (auto function : iface->getFunctions())
{
for (auto param : function->getParameters().getMembers())
{
DataType *datatype = param->getDataType()->getTrueDataType();
if (datatype->isFunction())
{
FunctionType *funType = dynamic_cast<FunctionType *>(datatype);
if (funType->getInterface() != iface)
{
interfacesNames.push_back(funType->getInterface()->getName());
}
if ((std::find(callbackTypesNames.begin(), callbackTypesNames.end(), funType->getName()) ==
callbackTypesNames.end()))
{
callbackTypes.push_back(funType);
callbackTypesNames.push_back(funType->getName());
}
}
}
}
for (auto functionType : iface->getFunctionTypes())
{
if ((std::find(callbackTypesNames.begin(), callbackTypesNames.end(), functionType->getName()) ==
callbackTypesNames.end()))
{
callbackTypes.push_back(functionType);
callbackTypesNames.push_back(functionType->getName());
}
}
for (auto functionType : callbackTypes)
{
data_list functionsInt;
data_list functionsExt;
data_list functionsAll;
for (auto fun : functionType->getCallbackFuns())
{
if ((std::find(interfacesNames.begin(), interfacesNames.end(), fun->getInterface()->getName()) !=
interfacesNames.end()))
{
data_map function;
function["name"] = fun->getName();
if (fun->getInterface() == iface)
{
functionsInt.push_back(function);
}
else
{
functionsExt.push_back(function);
}
functionsAll.push_back(function);
}
}
if (!functionsAll.empty())
{
data_map callbackType;
callbackType["name"] = functionType->getName();
callbackType["typenameName"] = getFunctionPrototype(nullptr, functionType);
callbackType["interfaceTypenameName"] =
getFunctionPrototype(nullptr, functionType, iface->getName() + "_interface");
if (!functionsInt.empty())
{
callbackType["callbacks"] = functionsInt;
callbackType["callbacksData"] = getFunctionTypeTemplateData(group, functionType);
callbackTypesInt.push_back(callbackType);
}
if (!functionsExt.empty())
{
callbackType["callbacks"] = functionsExt;
callbackTypesExt.push_back(callbackType);
}
callbackType["callbacks"] = functionsAll;
callbackTypesAll.push_back(callbackType);
}
}
}
data_map Generator::generateHashTableData(Interface *iface, const data_list &functions)
{
data_map hashTableInfo;
// Get function count and calculate optimal hash table size
uint32_t functionCount = static_cast<uint32_t>(functions.size());
uint32_t hashTableSize = ERPC_HASH_TABLE_MIN_SIZE;
// Find next power of 2 that gives target load factor
while (hashTableSize * ERPC_HASH_TABLE_TARGET_LOAD_FACTOR < functionCount &&
hashTableSize < ERPC_HASH_TABLE_MAX_SIZE)
{
hashTableSize *= 2;
}
// Check if we hit the size limit and report performance impact
double loadFactor = static_cast<double>(functionCount) / hashTableSize;
if (hashTableSize >= ERPC_HASH_TABLE_MAX_SIZE && loadFactor > ERPC_HASH_TABLE_TARGET_LOAD_FACTOR) {
Log::warning("Interface '%s': Hash table size limit reached (%d functions in %d-entry table)\n"
"Load factor: %.3f, Expected probes: %.1f\n"
"Consider splitting interface for better performance.\n",
iface->getName().c_str(), functionCount, hashTableSize,
loadFactor, 0.5 * (1 + 1/(1-loadFactor)));
}
Log::info("Hash table for '%s': size=%d, functions=%d, load_factor=%.3f\n",
iface->getName().c_str(), hashTableSize, functionCount, loadFactor);
hashTableInfo["size"] = make_data(hashTableSize);
hashTableInfo["functionCount"] = make_data(functionCount);
hashTableInfo["loadFactor"] = make_data(static_cast<double>(functionCount) / hashTableSize);
// Hash function implementation (Knuth multiplicative method)
auto hash_function_id = [hashTableSize](uint32_t id) -> uint32_t {
uint32_t hash = id;
hash = ((hash >> 16) ^ hash) * 0x45d9f3bU;
hash = ((hash >> 16) ^ hash) * 0x45d9f3bU;
hash = (hash >> 16) ^ hash;
return hash & (hashTableSize - 1);
};
// Initialize hash table array
vector<data_map> hashTable(hashTableSize);
for (uint32_t i = 0; i < hashTableSize; i++)
{
data_map entry;
entry["isEmpty"] = make_data(true);
entry["index"] = make_data(i);
entry["id"] = make_data(0U);
entry["name"] = make_data(string(""));
entry["comment"] = make_data(string("Empty"));
entry["probeDistance"] = make_data(0);
hashTable[i] = entry;
}
// Place functions in hash table using linear probing
uint32_t collisions = 0;
uint32_t maxProbe = 0;
for (size_t i = 0; i < functions.size(); ++i)
{
data_ptr funcPtr = functions[i];
assert(dynamic_cast<DataMap *>(funcPtr.get().get()));
DataMap *functionData = dynamic_cast<DataMap *>(funcPtr.get().get());
// Extract function ID and name from template data
uint32_t functionId = static_cast<uint32_t>(stoul(functionData->getmap()["id"]->getvalue()));
string functionName = functionData->getmap()["name"]->getvalue();
// Calculate hash position
uint32_t hashPos = hash_function_id(functionId);
uint32_t probeDistance = 0;
// Linear probing collision resolution
while (!hashTable[hashPos]["isEmpty"]->getvalue().empty() &&
hashTable[hashPos]["isEmpty"]->getvalue() != "true")
{
hashPos = (hashPos + 1) % hashTableSize;
probeDistance++;
if (probeDistance > 0 && probeDistance == 1)
{
collisions++;
}
}
// Insert function into hash table
data_map entry;
entry["isEmpty"] = make_data(false);
entry["index"] = make_data(hashPos);
entry["id"] = make_data(functionId);
entry["name"] = make_data(functionName);
entry["probeDistance"] = make_data(probeDistance);
if (probeDistance == 0)
{
entry["comment"] = make_data(string("Direct hash"));
}
else
{
entry["comment"] = make_data(string("Collision resolved (probe +") + to_string(probeDistance) + ")");
}
hashTable[hashPos] = entry;
if (probeDistance > maxProbe)
{
maxProbe = probeDistance;
}
}
// Convert hash table to template data
data_list hashTableEntries;
for (const auto& entry : hashTable)
{
hashTableEntries.push_back(entry);
}
// Statistics
hashTableInfo["entries"] = hashTableEntries;
hashTableInfo["collisions"] = make_data(collisions);
hashTableInfo["maxProbe"] = make_data(maxProbe);
hashTableInfo["primaryHitRate"] = make_data(static_cast<double>(functionCount - collisions) / functionCount * 100.0);
Log::info("Generated hash table for interface %s: size=%d, functions=%d, collisions=%d, maxProbe=%d\n",
iface->getName().c_str(), hashTableSize, functionCount, collisions, maxProbe);
return hashTableInfo;
}