forked from billvaglienti/ProtoGen
-
Notifications
You must be signed in to change notification settings - Fork 5
/
protocolparser.cpp
1804 lines (1477 loc) · 60.4 KB
/
protocolparser.cpp
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
#include "protocolparser.h"
#include "protocolstructuremodule.h"
#include "protocolpacket.h"
#include "enumcreator.h"
#include "protocolscaling.h"
#include "fieldcoding.h"
#include "protocolfloatspecial.h"
#include "protocolsupport.h"
#include "protocolbitfield.h"
#include "protocoldocumentation.h"
#include "shuntingyard.h"
#include <string>
#include <iostream>
#include <algorithm>
#include <filesystem>
#include <fstream>
// The version of the protocol generator is set here
const std::string ProtocolParser::genVersion = "3.2.a";
/*!
* \brief ProtocolParser::ProtocolParser
*/
ProtocolParser::ProtocolParser() :
currentxml(nullptr),
header(nullptr),
latexHeader(1),
latexEnabled(false),
nomarkdown(false),
nohelperfiles(false),
nodoxygen(false),
noAboutSection(false),
nocss(false),
tableOfContents(false)
{
}
/*!
* Destroy the protocol parser object
*/
ProtocolParser::~ProtocolParser()
{
// Delete all of our lists of new'ed objects
for(auto doc : documents)
delete doc;
documents.clear();
for(auto struc : structures)
delete struc;
structures.clear();
for(auto enu : enums)
delete enu;
enums.clear();
for(auto globalenu : globalEnums)
delete globalenu;
globalEnums.clear();
for(auto xmldoc : xmldocs)
delete xmldoc;
xmldocs.clear();
if(header != nullptr)
delete header;
}
/*!
* Parse the DOM from the xml file. This kicks off the auto code generation for the protocol
* \param filenames is the list of files to read the xml contents from. The
* first file is the master file that sets the protocol options
* \param path is the output path for generated files
* \return true if something was written to a file
*/
bool ProtocolParser::parse(std::string filename, std::string path, std::vector<std::string> otherfiles)
{
// Top level printout of the version information
std::cout << "ProtoGen version " << genVersion << std::endl;
std::filesystem::path filepath(filename);
// Remember the input path, in case there are files referenced by the main file
if(filepath.has_parent_path())
inputpath = ProtocolFile::sanitizePath(filepath.parent_path().string());
else
inputpath.clear();
// Also remember the name of the file, which we use for warning outputs
inputfile = filepath.filename().string();
std::fstream file(filename, std::ios_base::in);
if(!file.is_open())
{
std::cerr << filename << " : error: Failed to open protocol file" << std::endl;
return false;
}
currentxml = new XMLDocument();
xmldocs.push_back(currentxml);
if(currentxml->Parse(std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()).c_str()) != XML_SUCCESS)
{
file.close();
std::cerr << currentxml->ErrorStr() << std::endl;
return false;
}
// Done with the file
file.close();
// Set our output directory
// Make the path as short as possible
path = ProtocolFile::sanitizePath(path);
// There is an interesting case here: the user's output path is not
// empty, but after sanitizing it is empty, which implies the output
// path is the same as the current working directory. If this happens
// then mkpath() will fail because the input string cannot be empty,
// so we must test path.empty() again. Note that in this case the
// path definitely exists (since its our working directory)
std::error_code ec;
// Make sure the path exists
if(!path.empty())
std::filesystem::create_directories(path, ec);
// Make sure the path exists
if(!ec)
{
// Remember the output path for all users
support.outputpath = path;
}
else
{
std::cerr << "error: Failed to create output path: " << path << std::endl;
return false;
}
// The outer most element
XMLElement* docElem = currentxml->RootElement();
// This element must have the "Protocol" tag
if((docElem == nullptr) || (XMLUtil::StringEqual(docElem->Name(), "protocol") == false))
{
std::cerr << filename << " : error: Protocol tag not found in XML" << std::endl;
return false;
}
// Protocol options specified in the xml
support.sourcefile = inputpath + inputfile;
support.protoName = name = getAttribute("name", docElem->FirstAttribute());
if(support.protoName.empty())
{
std::cerr << filename << " : error: Protocol name not found in XML" << std::endl;
return false;
}
title = getAttribute("title", docElem->FirstAttribute());
api = getAttribute("api", docElem->FirstAttribute());
version = getAttribute("version", docElem->FirstAttribute());
comment = getAttribute("comment", docElem->FirstAttribute());
support.parse(docElem->FirstAttribute());
if(support.disableunrecognized == false)
{
// All the attributes we understand
std::vector<std::string> attriblist = {"name", "title", "api", "version", "comment"};
// and the ones understood by the protocol support
std::vector<std::string> supportlist = support.getAttriblist();
for(const XMLAttribute* a = docElem->FirstAttribute(); a != nullptr; a = a->Next())
{
std::string test = trimm(a->Name());
if(!contains(attriblist, test) && !contains(supportlist, test))
std::cerr << support.sourcefile << ":" << a->GetLineNum() << ":0: warning: Unrecognized attribute \"" + test + "\"" << std::endl;
}// for all the attributes
}// if we need to warn for unrecognized attributes
// The list of our output files
std::vector<std::string> fileNameList;
std::vector<std::string> filePathList;
// Build the top level module
createProtocolHeader(docElem);
// And record its file name
fileNameList.push_back(header->fileName());
filePathList.push_back(header->filePath());
// Now parse the contents of all the files. We do other files first since
// we expect them to be helpers that the main file may depend on.
for(std::size_t i = 0; i < otherfiles.size(); i++)
parseFile(otherfiles.at(i));
// Finally the main file
parseFile(filename);
// This is a resource file for bitfield testing
if(support.bitfieldtest && support.bitfield)
{
std::fstream btestfile("bitfieldtester.xml", std::ios_base::out);
// Raw string literal trick, I love this!
std::string filedata = (
#include "bitfieldtest.xml"
);
if(btestfile.is_open())
{
btestfile << filedata;
btestfile.close();
parseFile("bitfieldtester.xml");
ProtocolFile::deleteFile("bitfieldtester.xml");
}
}
// Output the global enumerations first, they will go in the main
// header file by default, unless the enum specifies otherwise
ProtocolHeaderFile enumfile(support);
ProtocolSourceFile enumSourceFile(support);
for(std::size_t i = 0; i < globalEnums.size(); i++)
{
EnumCreator* module = globalEnums.at(i);
module->parseGlobal();
// Don't output if hidden and we are omitting hidden items
if(module->isHidden() && !module->isNeverOmit() && support.omitIfHidden)
{
std::cout << "Skipping code output for hidden global enumeration " << module->getHierarchicalName() << std::endl;
continue;
}
enumfile.setModuleNameAndPath(module->getHeaderFileName(), module->getHeaderFilePath());
if(support.supportbool && (support.language == ProtocolSupport::c_language))
enumfile.writeIncludeDirective("stdbool.h", "", true);
enumfile.write(module->getOutput());
enumfile.makeLineSeparator();
enumfile.flush();
// If there is source-code available
std::string source = module->getSourceOutput();
if(!source.empty())
{
enumSourceFile.setModuleNameAndPath(module->getHeaderFileName(), module->getHeaderFilePath());
enumSourceFile.write(source);
enumSourceFile.makeLineSeparator();
enumSourceFile.flush();
fileNameList.push_back(enumSourceFile.fileName());
filePathList.push_back(enumSourceFile.filePath());
}
// Keep a list of all the file names we used
fileNameList.push_back(enumfile.fileName());
filePathList.push_back(enumfile.filePath());
}
// Now parse the global structures
for(std::size_t i = 0; i < structures.size(); i++)
{
ProtocolStructureModule* module = structures[i];
// Parse its XML and generate the output
module->parse();
// Keep a list of all the file names
fileNameList.push_back(module->getDefinitionFileName());
filePathList.push_back(module->getDefinitionFilePath());
fileNameList.push_back(module->getHeaderFileName());
filePathList.push_back(module->getHeaderFilePath());
fileNameList.push_back(module->getSourceFileName());
filePathList.push_back(module->getSourceFilePath());
fileNameList.push_back(module->getVerifySourceFileName());
filePathList.push_back(module->getVerifySourceFilePath());
fileNameList.push_back(module->getVerifyHeaderFileName());
filePathList.push_back(module->getVerifyHeaderFilePath());
fileNameList.push_back(module->getCompareSourceFileName());
filePathList.push_back(module->getCompareSourceFilePath());
fileNameList.push_back(module->getCompareHeaderFileName());
filePathList.push_back(module->getCompareHeaderFilePath());
fileNameList.push_back(module->getPrintSourceFileName());
filePathList.push_back(module->getPrintSourceFilePath());
fileNameList.push_back(module->getPrintHeaderFileName());
filePathList.push_back(module->getPrintHeaderFilePath());
fileNameList.push_back(module->getMapSourceFileName());
filePathList.push_back(module->getMapSourceFilePath());
fileNameList.push_back(module->getMapHeaderFileName());
filePathList.push_back(module->getMapHeaderFilePath());
}// for all top level structures
// And the global packets. We want to sort the packets into two batches:
// those packets which can be used by other packets; and those which cannot.
// This way we can parse the first batch ahead of the second
for(std::size_t i = 0; i < packets.size(); i++)
{
ProtocolPacket* packet = packets.at(i);
if(!isFieldSet(packet->getElement(), "useInOtherPackets"))
continue;
// Parse its XML
packet->parse();
// The structures have been parsed, adding this packet to the list
// makes it available for other packets to find as structure reference
structures.push_back(packet);
// Keep a list of all the file names
fileNameList.push_back(packet->getDefinitionFileName());
filePathList.push_back(packet->getDefinitionFilePath());
fileNameList.push_back(packet->getHeaderFileName());
filePathList.push_back(packet->getHeaderFilePath());
fileNameList.push_back(packet->getSourceFileName());
filePathList.push_back(packet->getSourceFilePath());
fileNameList.push_back(packet->getVerifySourceFileName());
filePathList.push_back(packet->getVerifySourceFilePath());
fileNameList.push_back(packet->getVerifyHeaderFileName());
filePathList.push_back(packet->getVerifyHeaderFilePath());
fileNameList.push_back(packet->getCompareSourceFileName());
filePathList.push_back(packet->getCompareSourceFilePath());
fileNameList.push_back(packet->getCompareHeaderFileName());
filePathList.push_back(packet->getCompareHeaderFilePath());
fileNameList.push_back(packet->getPrintSourceFileName());
filePathList.push_back(packet->getPrintSourceFilePath());
fileNameList.push_back(packet->getPrintHeaderFileName());
filePathList.push_back(packet->getPrintHeaderFilePath());
fileNameList.push_back(packet->getMapSourceFileName());
filePathList.push_back(packet->getMapSourceFilePath());
fileNameList.push_back(packet->getMapHeaderFileName());
filePathList.push_back(packet->getMapHeaderFilePath());
}
// And the packets which are not available for other packets
for(std::size_t i = 0; i < packets.size(); i++)
{
ProtocolPacket* packet = packets.at(i);
if(isFieldSet(packet->getElement(), "useInOtherPackets"))
continue;
// Parse its XML
packet->parse();
// Keep a list of all the file names
fileNameList.push_back(packet->getDefinitionFileName());
filePathList.push_back(packet->getDefinitionFilePath());
fileNameList.push_back(packet->getHeaderFileName());
filePathList.push_back(packet->getHeaderFilePath());
fileNameList.push_back(packet->getSourceFileName());
filePathList.push_back(packet->getSourceFilePath());
fileNameList.push_back(packet->getVerifySourceFileName());
filePathList.push_back(packet->getVerifySourceFilePath());
fileNameList.push_back(packet->getVerifyHeaderFileName());
filePathList.push_back(packet->getVerifyHeaderFilePath());
fileNameList.push_back(packet->getCompareSourceFileName());
filePathList.push_back(packet->getCompareSourceFilePath());
fileNameList.push_back(packet->getCompareHeaderFileName());
filePathList.push_back(packet->getCompareHeaderFilePath());
fileNameList.push_back(packet->getPrintSourceFileName());
filePathList.push_back(packet->getPrintSourceFilePath());
fileNameList.push_back(packet->getPrintHeaderFileName());
filePathList.push_back(packet->getPrintHeaderFilePath());
fileNameList.push_back(packet->getMapSourceFileName());
filePathList.push_back(packet->getMapSourceFilePath());
fileNameList.push_back(packet->getMapHeaderFileName());
filePathList.push_back(packet->getMapHeaderFilePath());
}
// Parse all of the documentation
for(std::size_t i = 0; i < documents.size(); i++)
{
ProtocolDocumentation* doc = documents.at(i);
doc->parse();
}
if(!nohelperfiles)
{
// Auto-generated files for coding
ProtocolScaling(support).generate(fileNameList, filePathList);
FieldCoding(support).generate(fileNameList, filePathList);
ProtocolFloatSpecial(support).generate(fileNameList, filePathList);
}
// Code for testing bitfields
if(support.bitfieldtest && support.bitfield)
ProtocolBitfield::generatetest(support);
if(!nomarkdown)
outputMarkdown(support.bigendian, inlinecss);
#ifndef _DEBUG
if(!nodoxygen)
outputDoxygen();
#endif
// The last bit of the protocol header
finishProtocolHeader();
// This is fun...replace all the temporary files with real ones if needed
for(std::size_t i = 0; i < fileNameList.size(); i++)
ProtocolFile::copyTemporaryFile(filePathList.at(i), fileNameList.at(i));
// If we are putting the files in our local directory then we don't just want an empty string in our printout
if(path.empty())
path = "./";
std::cout << "Generated protocol files in " << path << std::endl;
return true;
}// ProtocolParser::parse
/*!
* Parses a single XML file handling any require tags to flatten a file
* heirarchy into a single flat structure
* \param xmlFilename is the file to parse
*/
bool ProtocolParser::parseFile(std::string xmlFilename)
{
// Path contains the path and file name and extension
std::filesystem::path path(xmlFilename);
// We allow each xml file to alter the global filenames used, but only for the context of that xml.
ProtocolSupport localsupport(support);
std::string absolutepathname;
if(xmlFilename.at(0) == ':')
absolutepathname = xmlFilename;
else
absolutepathname = std::filesystem::absolute(path).string();
// Don't parse the same file twice
if(contains(filesparsed, absolutepathname))
return false;
// Keep a record of what we have already parsed, so we don't parse the same file twice
filesparsed.push_back(absolutepathname);
std::cout << "Parsing file " << ProtocolFile::sanitizePath(path.parent_path().string()) << path.filename().string() << std::endl;
std::fstream xmlFile(xmlFilename, std::ios_base::in);
if(!xmlFile.is_open())
{
std::string warning = "error: Failed to open xml protocol file " + xmlFilename;
std::cerr << warning << std::endl;
return false;
}
currentxml = new XMLDocument();
xmldocs.push_back(currentxml);
std::string contents = std::string((std::istreambuf_iterator<char>(xmlFile)), std::istreambuf_iterator<char>());
// Done with the file
xmlFile.close();
// Error parsing
std::string error;
//int errorLine, errorCol;
currentxml = new XMLDocument();
// Extract XML data
if(currentxml->Parse(contents.c_str()) != XML_SUCCESS)
{
std::cerr << currentxml->ErrorStr() << std::endl;
delete currentxml;
if(xmldocs.size() > 0)
currentxml = xmldocs.back();
else
currentxml = nullptr;
return false;
}
else
xmldocs.push_back(currentxml);
// The outer most element
XMLElement* docElem = currentxml->RootElement();
// This element must have the "Protocol" tag
if((docElem == nullptr) || (XMLUtil::StringEqual(docElem->Name(), "protocol") == false))
{
std::string warning = xmlFilename + ":0:0: error: 'Protocol' tag not found in file";
std::cerr << warning << std::endl;
return false;
}
// Protocol file options specified in the xml
localsupport.parseFileNames(docElem->FirstAttribute());
localsupport.sourcefile = xmlFilename;
for(const XMLElement* element = docElem->FirstChildElement(); element != nullptr; element = element->NextSiblingElement())
{
std::string nodename = toLower(trimm(element->Name()));
// Import another file recursively
// File recursion is handled first so that ordering is preserved
// This effectively creates a single flattened XML structure
if( nodename == "require" )
{
std::string subfile = getAttribute("file", element->FirstAttribute());
if( subfile.empty() )
{
std::string warning = xmlFilename + ": warning: file attribute missing from \"Require\" tag";
std::cerr << warning << std::endl;
}
else
{
if(!endsWith(subfile, ".xml"))
subfile += ".xml";
// The new file is relative to this file
parseFile(ProtocolFile::sanitizePath(path.parent_path().string()) + subfile);
}
}
else if( nodename == "struct" || nodename == "structure" )
{
ProtocolStructureModule* module = new ProtocolStructureModule( this, localsupport, api, version );
// Remember the XML
module->setElement(element);
structures.push_back( module );
}
else if( nodename == "enum" || nodename == "enumeration" )
{
EnumCreator* Enum = new EnumCreator( this, nodename, localsupport );
Enum->setElement(element);
globalEnums.push_back( Enum );
alldocumentsinorder.push_back( Enum );
}
// Define a packet
else if( nodename == "packet" || nodename == "pkt" )
{
ProtocolPacket* packet = new ProtocolPacket( this, localsupport, api, version );
packet->setElement(element);
packets.push_back( packet );
alldocumentsinorder.push_back( packet );
}
else if ( nodename == "doc" || contains(nodename, "document"))
{
ProtocolDocumentation* document = new ProtocolDocumentation( this, nodename, localsupport );
document->setElement(element);
documents.push_back( document );
alldocumentsinorder.push_back( document );
}
else
{
//TODO
}
}
return true;
}// ProtocolParser::parseFile
/*!
* Create the header file for the top level module of the protocol
* \param docElem is the "protocol" element from the DOM
*/
void ProtocolParser::createProtocolHeader(const XMLElement* docElem)
{
// Build the header file
header = new ProtocolHeaderFile(support);
// The file name
header->setModuleNameAndPath(name + "Protocol", support.outputpath);
// Construct the file comment that goes in the \file block
std::string filecomment = "\\mainpage " + name + " protocol stack\n\n" + comment + "\n\n";
// The protocol enumeration API, which can be empty
if(!api.empty())
{
// Make sure this is only a number
bool ok = false;
int64_t number = ShuntingYard::toInt(api, &ok);
if(ok && number > 0)
{
// Turn it back into a string
api = std::string(api);
filecomment += "The protocol API enumeration is incremented anytime the protocol is changed in a way that affects compatibility with earlier versions of the protocol. The protocol enumeration for this version is: " + api + "\n\n";
}
else
api.clear();
}// if we have API enumeration
// The protocol version string, which can be empty
if(!version.empty())
filecomment += "The protocol version is " + version + "\n\n";
// A long comment that should be wrapped at 80 characters in the \file block
header->setFileComment(filecomment);
header->makeLineSeparator();
// Includes
if(support.supportbool)
header->writeIncludeDirective("stdbool.h", "", true);
header->writeIncludeDirective("stdint.h", std::string(), true);
// Add other includes
outputIncludes(name, *header, docElem);
header->makeLineSeparator();
// API macro
if(!api.empty())
{
header->makeLineSeparator();
header->write("//! \\return the protocol API enumeration\n");
header->write("#define get" + name + "Api() " + api + "\n");
}
// Version macro
if(!version.empty())
{
header->makeLineSeparator();
header->write("//! \\return the protocol version string\n");
header->write("#define get" + name + "Version() \"" + version + "\"\n");
}
// Translation macro
header->makeLineSeparator();
header->write("// Translation provided externally. The macro takes a `const char *` and returns a `const char *`\n");
header->write("#ifndef translate" + name + "\n");
header->write(" #define translate" + name + "(x) x\n");
header->write("#endif");
header->makeLineSeparator();
// We need to flush this to disk now, because others may try to open this file and append it
header->flush();
}// ProtocolParser::createProtocolHeader
void ProtocolParser::finishProtocolHeader(void)
{
// We need to re-open this file because others may have written to it and
// we want to append after their write (This is the whole reaons that
// finishProtocolHeader() is separate from createProtocolHeader()
header->setModuleNameAndPath(name + "Protocol", support.outputpath);
header->makeLineSeparator();
// We want these prototypes to be the last things written to the file, because support.pointerType may be defined above
header->write("\n");
header->write("// The prototypes below provide an interface to the packets.\n");
header->write("// They are not auto-generated functions, but must be hand-written\n");
header->write("\n");
header->write("//! \\return the packet data pointer from the packet\n");
header->write("uint8_t* get" + name + "PacketData(" + support.pointerType + " pkt);\n");
header->write("\n");
header->write("//! \\return the packet data pointer from the packet, const\n");
header->write("const uint8_t* get" + name + "PacketDataConst(const " + support.pointerType + " pkt);\n");
header->write("\n");
header->write("//! Complete a packet after the data have been encoded\n");
header->write("void finish" + name + "Packet(" + support.pointerType + " pkt, int size, uint32_t packetID);\n");
header->write("\n");
header->write("//! \\return the size of a packet from the packet header\n");
header->write("int get" + name + "PacketSize(const " + support.pointerType + " pkt);\n");
header->write("\n");
header->write("//! \\return the ID of a packet from the packet header\n");
header->write("uint32_t get" + name + "PacketID(const " + support.pointerType + " pkt);\n");
header->write("\n");
header->flush();
}
/*!
* Output a long string of text which should be wrapped at 80 characters.
* \param file receives the output
* \param prefix precedes each line (for example "//" or " *"
* \param text is the long text string to output. If text is empty
* nothing is output
*/
void ProtocolParser::outputLongComment(ProtocolFile& file, const std::string& prefix, const std::string& text)
{
file.write(outputLongComment(prefix, text));
}// ProtocolParser::outputLongComment
/*!
* Output a long string of text which should be wrapped at 80 characters.
* \param prefix precedes each line (for example "//" or " *"
* \param text is the long text string to output. If text is empty
* nothing is output.
* \return The formatted text string.
*/
std::string ProtocolParser::outputLongComment(const std::string& prefix, const std::string& text)
{
return reflowComment(text, prefix, 80);
}// ProtocolParser::outputLongComment
/*!
* Get a correctly reflowed comment from a DOM
* \param e is the DOM to get the comment from
* \return the correctly reflowed comment, which could be empty
*/
std::string ProtocolParser::getComment(const XMLElement* e)
{
return reflowComment(e->Attribute("comment"));
}
/*!
* Take a comment line which may have some unusual spaces and line feeds that
* came from the xml formatting and reflow it for our needs.
* \param text is the raw comment from the xml.
* \param prefix precedes each line (for example "//" or " *"
* \return the reflowed comment.
*/
std::string ProtocolParser::reflowComment(const std::string& text, const std::string& prefix, std::size_t charlimit)
{
// Remove leading and trailing white space
std::string output = trimm(text);
// Convert to unix style line endings, just in case
replaceinplace(output, "\r\n", "\n");
// Separate by blocks that have \verbatim surrounding them
std::vector<std::string> blocks = split(output, "\\verbatim");
// Empty the output string so we can build the output up
output.clear();
for(std::size_t b = 0; b < blocks.size(); b++)
{
// odd blocks are "verbatim", even blocks are not
if((b & 0x01) == 1)
{
// Separate the paragraphs, as given by single line feeds
std::vector<std::string> paragraphs = split(blocks.at(b), "\n");
if(prefix.empty())
{
for(std::size_t i = 0; i < paragraphs.size(); i++)
output += paragraphs[i] + "\n";
}
else
{
// Output with the prefix
for(std::size_t i = 0; i < paragraphs.size(); i++)
output += prefix + " " + paragraphs[i] + "\n";
}
}
else
{
// Separate the paragraphs, as given by dual line feeds
std::vector<std::string> paragraphs = split(blocks.at(b), "\n\n");
for(std::size_t i = 0; i < paragraphs.size(); i++)
{
// Replace line feeds with spaces
replaceinplace(paragraphs[i], "\n", " ");
// Replace tabs with spaces
replaceinplace(paragraphs[i], "\t", " ");
std::size_t length = 0;
// Break it apart into words
std::vector<std::string> list = split(paragraphs[i], " ");
// Now write the words one at a time, wrapping at character length
for (std::size_t j = 0; j < list.size(); j++)
{
// Length of the word plus the preceding space
std::size_t wordLength = list.at(j).length() + 1;
if(charlimit > 0)
{
if((length != 0) && (length + wordLength > charlimit))
{
// Terminate the previous line
output += "\n";
length = 0;
}
}
// All lines in the comment block start with the prefix
if(length == 0)
{
output += prefix;
length += prefix.length();
}
else
output += " ";
output += list.at(j);
length += wordLength;
}// for all words in the comment
// Paragraph break, except for the last paragraph
if(i < paragraphs.size() - 1)
output += "\n" + prefix + "\n";
}// for all paragraphs
}// if block is not verbatim
}// for all blocks
return output;
}
/*!
* Return a list of XNLNodes that are direct children and have a specific tag
* name. This gets just children, not grand children.
* \param node is the parent node.
* \param tag is the tag name to look for.
* \param tag2 is a second optional tag name to look for.
* \param tag3 is a third optional tag name to look for.
* \return a list of XMLNodes.
*/
std::vector<const XMLElement*> ProtocolParser::childElementsByTagName(const XMLElement* node, std::string tag, std::string tag2, std::string tag3)
{
std::vector<const XMLElement*> list;
// Now just the ones with the tag(s) we want
for(const XMLElement* child = node->FirstChildElement(); child != nullptr; child = child->NextSiblingElement())
{
if(contains(child->Value(), tag))
list.push_back(child);
else if(contains(child->Value(), tag2))
list.push_back(child);
else if(contains(child->Value(), tag3))
list.push_back(child);
}
return list;
}// ProtocolParser::childElementsByTagName
/*!
* Return the value of an attribute from a node map
* \param name is the name of the attribute to return. name is not case sensitive
* \param attr is the root attribute from a DOM element.
* \param defaultIfNone is returned if no name attribute is found.
* \return the value of the name attribute, or defaultIfNone if none found
*/
std::string ProtocolParser::getAttribute(const std::string &name, const XMLAttribute *attr, const std::string &defaultIfNone)
{
for( const XMLAttribute* a = attr; a; a = a->Next() )
{
if ( XMLUtil::StringEqual( a->Name(), name.c_str() ) )
{
return trimm(a->Value());
}
}
return defaultIfNone;
}// ProtocolParser::getAttribute
/*!
* Parse all enumerations which are direct children of a DomNode. The
* enumerations will be stored in the global list
* \param parent is the hierarchical name of the object which owns the new enumeration
* \param node is parent node
*/
void ProtocolParser::parseEnumerations(const std::string& parent, const XMLNode* node)
{
const XMLElement* element = node->ToElement();
if(element == nullptr)
return;
// Interate through the child elements
for(const XMLElement* e = element->FirstChildElement(); e != nullptr; e = e->NextSiblingElement())
{
// Look at those which are tagged "enum"
if(toLower(e->Name()) == "enum")
parseEnumeration(parent, e);
}
}// ProtocolParser::parseEnumerations
/*!
* Parse a single enumeration given by a DOM element. This will also
* add the enumeration to the global list which can be searched with
* lookUpEnumeration().
* \param parent is the hierarchical name of the object which owns the new enumeration
* \param element is the DomElement that represents this enumeration
* \return a pointer to the newly created enumeration object. This pointer could be null.
*/
const EnumCreator* ProtocolParser::parseEnumeration(const std::string& parent, const XMLElement* element)
{
EnumCreator* Enum = new EnumCreator(this, parent, support);
Enum->setElement(element);
Enum->parse();
// If we have a hidden field, and we are not supposed to omit code for that
// field, we treat it as null. This is because we *must* omit the code in
// order to adhere to the encoding packet rules. This may break some code
// if other fields depend on the hidden field.
if(Enum->isHidden() && !Enum->isNeverOmit() && support.omitIfHidden)
{
// This is not a warning, just useful information
std::cout << "Skipping code output for enumeration " << Enum->getHierarchicalName() << std::endl;
delete Enum;
Enum = nullptr;
}
else
enums.push_back(Enum);
return Enum;
}// ProtocolParser::parseEnumeration
/*!
* Output all include directions which are direct children of a DomNode
* \param parent is the hierarchical name of the owning object
* \param file receives the output
* \param node is parent node
*/
void ProtocolParser::outputIncludes(const std::string& parent, ProtocolFile& file, const XMLNode* node) const
{
outputIncludes(parent, file, node->ToElement());
}// ProtocolParser::outputIncludes
/*!
* Output all include directions which are direct children of an element
* \param parent is the hierarchical name of the owning object
* \param file receives the output
* \param node is parent node
*/
void ProtocolParser::outputIncludes(const std::string& parent, ProtocolFile& file, const XMLElement* element) const
{
if(element == nullptr)
return;
// Interate through the child elements
for(const XMLElement* e = element->FirstChildElement(); e != nullptr; e = e->NextSiblingElement())
{
// Look at those which are tagged "include"
if(toLower(trimm(e->Name())) == "include")
{
std::string include;
std::string comment;
bool global = false;
for(const XMLAttribute* a = e->FirstAttribute(); a != nullptr; a = a->Next())
{
std::string attrname = toLower(trimm(a->Name()));
if(attrname == "name")
include = trimm(a->Value());
else if(attrname == "comment")
comment = trimm(a->Value());
else if(attrname == "global")
global = ProtocolParser::isFieldSet(a->Value());
else if(support.disableunrecognized == false)
ProtocolDocumentation::emitWarning(support.sourcefile, parent + ": " + include, "Unrecognized attribute", a);