-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDriver.cpp
More file actions
1120 lines (976 loc) · 34.9 KB
/
Driver.cpp
File metadata and controls
1120 lines (976 loc) · 34.9 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
//===- Driver.cpp ---------------------------------------------------===//
//
// Copyright (C) 2024-2026 Ninefold
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//===----------------------------------------------------------------===//
#include "Driver.hpp"
#include <Common/APInt.hpp>
#include <Common/EnumArray.hpp>
#include <Common/IntrusiveRefCntPtr.hpp>
#include <Common/MMatch.hpp>
#include <Common/MaybeBox.hpp>
#include <Common/PointerIntPair.hpp>
#include <Common/Poly.hpp>
#include <Common/Result.hpp>
#include <Common/SmallStr.hpp>
#include <Common/StringSwitch.hpp>
#include <Common/Twine.hpp>
#include <Support/BinaryToText.hpp>
#include <Support/Filesystem.hpp>
#include <Support/InitDriver.hpp>
#include <Support/Logging.hpp>
#include <Support/MemoryBuffer.hpp>
#include <Support/MemoryBufferRef.hpp>
#include <Support/Path.hpp>
#include <Support/Process.hpp>
#include <Support/ScopedSave.hpp>
#include <Support/Signals.hpp>
#include <Support/raw_ostream.hpp>
#include <exi/Basic/ExiOptions.hpp>
#include <exi/Basic/Runes.hpp>
#include <exi/Basic/StringTables.hpp>
#include <exi/Basic/XMLContainer.hpp>
#include <exi/Basic/XMLCompare.hpp>
#include <exi/Basic/XMLManager.hpp>
#include <exi/Stream/OrderedReader.hpp>
#include <exi/Stream/OrderedWriter.hpp>
#include <exi/Encode/BodyEncoder.hpp>
#include <exi/Encode/NamespaceContextStack.hpp>
#include <exi/Encode/XMLSerializer.hpp>
#include <exi/Decode/BodyDecoder.hpp>
#include <exi/Decode/StreamDeserializer.hpp>
#include <exi/Decode/XMLDeserializer.hpp>
#include <algorithm>
#include <dtl/dtl.hpp>
#include <rapidxml.hpp>
#define DEBUG_TYPE "__DRIVER__"
#define TEST_LARGE_EXAMPLES 0
#define STRESS_TEST_DECODING 0
using namespace exi;
static constinit Option<String> EXIFICIENT_DIR = std::nullopt;
ALWAYS_INLINE static constexpr
void SetLogLevel([[maybe_unused]] LogLevelType NewLevel) {
#if EXI_LOGGING
exi::DebugFlag = NewLevel;
#endif
}
static void RunDumps(XMLManager& Mgr, bool Conforming = false) {
using namespace root;
DumpOptions Opts {.Conforming = Conforming};
XMLDump::full(Mgr, "examples/022.xml", Opts);
XMLDump::full(Mgr, "examples/044.xml", Opts);
XMLDump::full(Mgr, "examples/079.xml", Opts);
XMLDump::full(Mgr, "examples/085.xml", Opts);
XMLDump::full(Mgr, "examples/103.xml", Opts);
XMLDump::full(Mgr, "examples/116.xml", Opts);
XMLDump::full(Mgr, "examples/Namespace.xml", Opts);
XMLDump::full(Mgr, "examples/SortTest.xml", Opts);
XMLDump::full(Mgr, "examples/Thai.xml", Opts);
// Without prints this runs in 0.2 seconds!
// XMLDump::full(Mgr, "large-examples/treebank_e.xml", Opts);
}
static void TestSchema(StrRef Name, ExiOptions::PreserveOpts Preserve) {
ExiOptions Opts { .Preserve = Preserve };
Opts.SchemaID.emplace(nullptr);
auto S = decode::BuiltinSchema::New(Opts);
exi_assert(S, "Invalid BuiltinSchema");
WithColor(outs(), raw_ostream::BRIGHT_BLUE) << Name << ":\n";
S->dump();
}
static void TestSchemas() {
ScopedSave S(DebugFlag, LogLevel::INFO);
TestSchema("Preserve.{CM}", {
.Comments = true,
});
TestSchema("Preserve.{CM, DT}", {
.Comments = true,
.DTDs = true,
});
TestSchema("Preserve.{PI, NS}", {
.PIs = true,
.Prefixes = true,
});
TestSchema("Preserve.All", {
.Comments = true,
.DTDs = true,
.PIs = true,
.Prefixes = true,
});
}
//////////////////////////////////////////////////////////////////////////
// Decoding
static int Decode(ExiDecoder& Decoder, MemoryBufferRef MB) {
LOG_INFO("Decoding header...");
if (auto E = Decoder.decodeHeader(MB)) {
errs() << E << '\n';
return 1;
}
LOG_INFO("Decoding body...");
if (auto E = Decoder.decodeBody()) {
errs() << E << '\n';
return 1;
}
INFO_ONLY(dbgs() << '\n');
return 0;
}
static int Decode(ExiDecoder& Decoder, MemoryBufferRef MB, Deserializer* S) {
LOG_INFO("Decoding header...");
if (auto E = Decoder.decodeHeader(MB)) {
errs() << E << '\n';
return 1;
}
LOG_INFO("Decoding body...");
if (auto E = Decoder.decodeBody(S)) {
errs() << E << '\n';
return 1;
}
INFO_ONLY(dbgs() << '\n');
return 0;
}
static int Decode(XMLManager* Mgr, StrRef File, ExiOptions& Opts) {
XMLContainerRef Exi
= Mgr->getOptXMLRef(File, errs())
.expect("could not locate file!");
auto MB = Exi.getBufferRef();
LOG_INFO("Decoding: \"{}\"", File);
ExiDecoder Decoder(Opts);
return Decode(Decoder, MB);
}
//////////////////////////////////////////////////////////////////////////
// Encoding
static int Encode(XMLManager* Mgr, StrRef File, ExiHeader& Opts) {
XMLDocument& Xml
= Mgr->getOptXMLDocument(File, errs())
.expect("could not locate file!");
LOG_INFO("Encoding: \"{}\"", File);
// ExiDecoder Decoder(Opts, errs());
// return Decode(Decoder, MB);
return 0;
}
//////////////////////////////////////////////////////////////////////////
// Implementation
template <int Total>
EXI_NO_INLINE EXI_NODEBUG static void PrintIters(int NIters) {
float Percent = (float(NIters) / float(Total)) * 100.f;
outs() << format(" {: >3.0f}% - {} iterations\n", Percent, NIters);
}
template <int Total, int Divisor = 10>
EXI_INLINE static constexpr bool CheckIters(int& NIters) {
exi_assume(NIters > -1);
const bool Out = (NIters++ < Total);
if EXI_UNLIKELY(NIters % (Total / Divisor) == 0)
PrintIters<Total>(NIters);
return Out;
}
static int TestSchemalessDecoding(XMLManagerRef SharedMgr);
//////////////////////////////////////////////////////////////////////////
// Diff
static int CalcSpacesSize(StrRef LHS, StrRef RHS) {
usize Size = std::min(LHS.size(), RHS.size());
return Log2_64_Ceil(Size) / 4 + 1;
}
/// Prints a pretty byte diff
static void ByteDiffViewer(StrRef Original, StrRef Encoded,
usize BreakOn = 4, bool Hex = false,
bool LabelX = false, usize SkipY = 0) {
using enum raw_ostream::Colors;
static constexpr StrRef VSplit = " \xE2\x94\x82 "_str;
const usize BreakOnX = (BreakOn > 0) ? BreakOn : 1;
usize Width = Hex ? 2 : 8;
usize BlockSize = (BreakOnX * (Width + 1)) - 1;
const int Padding = CalcSpacesSize(Original, Encoded);
usize Count = SkipY, Ix = 0;
if (SkipY > 0) {
if (SkipY > (Original.size() / BreakOnX) + 1) {
LOG_WARN("SkipY of {} is larger than the buffer!", SkipY);
return;
}
Original = Original.drop_front(SkipY * BreakOnX);
Encoded = Encoded.drop_front(SkipY * BreakOnX);
}
SmallStr<0> LHS, RHS;
raw_svector_ostream LOS(LHS), ROS(RHS);
LOS.enable_colors(true); ROS.enable_colors(true);
auto WriteByte = [Hex](raw_ostream& OS, char Byte) {
if (!Hex)
OS << format("{:08b} ", Byte);
else
OS << format("{:02x} ", Byte);
};
WithColor OS(errs(), BRIGHT_WHITE);
auto DumpData = [&, BreakOnX, Padding](){
OS << format("0x{:0{}x}", (Count * BreakOnX), Padding)
<< VSplit
<< LHS << BRIGHT_WHITE << VSplit
<< RHS << BRIGHT_WHITE << VSplit << '\n';
LHS.clear(); RHS.clear();
++Count; Ix = 0;
};
SmallStr<64> CenterString;
CenterString.reserve((BlockSize + 1) * 3);
for (usize N = 0; N < BreakOnX; ++N)
CenterString.append(Hex ? u8"───"_str : u8"─────────"_str);
CenterString.pop_back_n(3);
auto PrintLine = [&] (StrRef LS, StrRef C, StrRef RS) {
OS << indent(2 + Padding)
<< LS << CenterString
<< C << CenterString
<< RS << '\n';
};
auto PrintEmptyLine = [&] (StrRef S = "") {
exi_invariant(S.size() <= 5, "This may break formatting!");
OS << left_justify(S, 2 + Padding) << VSplit
<< indent(BlockSize) << VSplit
<< indent(BlockSize) << VSplit << '\n';
};
/*Print Top*/ {
PrintLine(u8" ┌─", u8"─┬─", u8"─┐ ");
OS << indent(2 + Padding) << VSplit
<< center_justify("Original", BlockSize) << VSplit
<< center_justify("Encoded", BlockSize) << VSplit << '\n';
PrintLine(u8" ├─", u8"─┼─", u8"─┤ ");
} if (LabelX) {
OS << indent(2 + Padding);
for (int Groups = 0; Groups < 2; ++Groups) {
OS << VSplit << left_justify("00", Width);
for (usize I = 1; I < BreakOn; ++I) {
auto N = fmt::format("{:02x}", I);
OS << ' ' << left_justify(N, Width);
}
}
OS << VSplit << '\n';
// Empty line
PrintEmptyLine(SkipY > 0 ? "..." : "");
}
for (auto [O, E] : exi::zip(Original, Encoded)) {
auto Color = (O == E) ? BRIGHT_GREEN : BRIGHT_RED;
WriteByte(LOS << Color, O);
WriteByte(ROS << Color, E);
if (++Ix >= BreakOnX) {
LHS.pop_back(); RHS.pop_back();
DumpData();
OS << BRIGHT_WHITE;
}
}
if (!LHS.empty()) {
usize Remaining = BreakOnX - Ix;
usize Spaces = (Remaining * (Width + 1)) - 1;
LHS.append(Spaces, ' ');
RHS.append(Spaces, ' ');
DumpData();
}
/*Print Bottom*/ {
PrintEmptyLine();
PrintLine(u8" └─", u8"─┴─", u8"─┘ ");
}
}
static void PadByteDiffViewer(StrRef Original, StrRef Encoded,
usize BreakOn = 4, bool Hex = false,
bool LabelX = false, usize SkipY = 0) {
if (Original.size() > Encoded.size()) {
std::string E(Encoded.data(), Encoded.size());
E.resize(Original.size(), '\0');
StrRef EData(E.data(), E.size());
return ByteDiffViewer(Original, EData, BreakOn, Hex, LabelX, SkipY);
} else if (Original.size() < Encoded.size()) {
std::string O(Original.data(), Original.size());
O.resize(Encoded.size(), '\0');
StrRef OData(O.data(), O.size());
return ByteDiffViewer(OData, Encoded, BreakOn, Hex, LabelX, SkipY);
}
return ByteDiffViewer(Original, Encoded, BreakOn, Hex, LabelX, SkipY);
}
static void PrintByteCompareStrings(bool Val) {
if (Val) {
WithColor(errs(), raw_ostream::BRIGHT_GREEN)
<< "Encoded files are the same!\n";
} else {
WithColor(errs(), raw_ostream::BRIGHT_RED)
<< "Encoded files are NOT the same.\n";
}
}
static void ByteCompareStrings(StrRef Original, StrRef Encoded) {
auto AllZeros = [] (StrRef S) -> bool {
for (char C : S)
if (C != 0)
return false;
return true;
};
usize OSize = Original.size(), ESize = Encoded.size();
if (OSize > ESize) {
bool SameFront = (Original.take_front(ESize) == Encoded);
PrintByteCompareStrings(SameFront
&& AllZeros(Original.take_back(OSize - ESize)));
} else if (OSize < ESize) {
bool SameFront = (Original == Encoded.take_front(OSize));
PrintByteCompareStrings(SameFront
&& AllZeros(Encoded.take_back(ESize - OSize)));
} else {
PrintByteCompareStrings(Original == Encoded);
}
}
//////////////////////////////////////////////////////////////////////////
// Encode/Decode
namespace {
struct CompareMetadata {
Vec<String> RawCommands;
Vec<std::tuple<String, String, ExiOptions::PreserveOpts>> OldToNewMapping;
public:
void reserve(usize N) {
RawCommands.reserve(N);
OldToNewMapping.reserve(N);
}
};
/// EnCode/DeCode Test Runner
class ECDCTestRunner {
XMLManagerRef Mgr;
StrRef ExamplePath = "examples";
mutable ExiOptions Opts;
CompareMetadata* Cmds = nullptr;
public:
ECDCTestRunner(XMLManagerRef Mgr, StrRef Folder,
AlignKind K, ExiOptions::PreserveOpts P,
CompareMetadata* Cmds = nullptr)
: Mgr(std::move(Mgr)), ExamplePath(Folder), Opts{
.Alignment = K, .Preserve = P,
.SchemaID = Some(nullptr)},
Cmds(Cmds) {
}
ECDCTestRunner(XMLManagerRef Mgr,
AlignKind K, ExiOptions::PreserveOpts P,
CompareMetadata* Cmds = nullptr)
: ECDCTestRunner(std::move(Mgr), "examples", K, P, Cmds) {
}
/// Runs Decoder -> Encoder -> Decoder.
int runWithRet(StrRef ExiFile, StrRef XmlFile,
bool Diff = false, bool Dump = false, usize Skip = 0) const;
/// Invokes run, exits on failure.
void run(StrRef ExiFile, StrRef XmlFile,
bool Diff = false, bool Dump = false, usize Skip = 0) const;
/// Invokes run without exi, exits on failure.
void runXml(StrRef XmlFile, bool Diff = false,
bool Dump = false, usize Skip = 0) const {
this->run(""_str, XmlFile, Diff, Dump, Skip);
}
ExiOptions* operator->() { return &Opts; }
const ExiOptions* operator->() const { return &Opts; }
};
} // namespace `anonymous`
static Expected<std::string> GetAbsoluteFilename(StrRef File) {
std::string FileName = File.str();
if (!sys::path::is_absolute(File)) {
SmallStr<256> Path(File);
if (auto EC = sys::fs::make_absolute(Path))
return errorCodeToError(EC);
FileName = static_cast<std::string>(Path);
}
StrRef Parent = sys::path::parent_path(FileName);
if (auto EC = sys::fs::create_directories(Parent))
return errorCodeToError(EC);
return FileName;
}
/// Writes contents to a file.
static Error WriteFile(StrRef File, StrRef Contents) {
Expected<std::string> ErrOrFileName
= GetAbsoluteFilename(File);
if (!ErrOrFileName)
return ErrOrFileName.takeError();
std::string FileName = std::move(ErrOrFileName.get());
std::error_code EC;
raw_fd_ostream OS(FileName, EC,
sys::fs::CD_CreateAlways,
sys::fs::FA_Write, sys::fs::OF_None);
if (EC)
return errorCodeToError(EC);
OS.write(Contents.data(), Contents.size());
return Error::success();
}
static Error WriteCmdsToFile(StrRef File, const Vec<String>& Contents) {
Expected<std::string> ErrOrFileName
= GetAbsoluteFilename(File);
if (!ErrOrFileName)
return ErrOrFileName.takeError();
std::string FileName = std::move(ErrOrFileName.get());
std::error_code EC;
raw_fd_ostream OS(FileName, EC,
sys::fs::CD_CreateAlways,
sys::fs::FA_Write, sys::fs::OF_None);
if (EC)
return errorCodeToError(EC);
#if EXI_ON_WIN32
OS << "@echo off\n\n";
#endif
for (const String& Line : Contents)
OS.write(Line.data(), Line.size()) << '\n';
OS.flush();
return Error::success();
}
static void WriteExificientCmds(const Vec<String>& Contents) {
constexpr StrRef OutputFile =
#if EXI_ON_WIN32
"examples/out/ExificientCmds.bat";
#else
"examples/out/ExificientCmds.sh";
#endif
Error E = WriteCmdsToFile(OutputFile, Contents);
logAllUnhandledErrors(std::move(E), errs(), "Errors creating ExificientCmds");
}
static void WriteExificientCmds(const CompareMetadata& Contents) {
return WriteExificientCmds(Contents.RawCommands);
}
static void AddExificientCmdOpts(raw_ostream& OS, const ExiOptions& Opts) {
if (!Opts.SchemaID || !*Opts.SchemaID)
OS << "-noSchema ";
else
OS << "-schema " << *Opts.SchemaID->get() << ' ';
if (Opts.Strict)
OS << "-strict ";
if (Opts.Preserve.Prefixes)
OS << "-preservePrefixes ";
if (Opts.Preserve.Comments)
OS << "-preserveComments ";
if (Opts.Preserve.PIs)
OS << "-preservePIs ";
if (Opts.Preserve.DTDs)
OS << "-preserveDTDs ";
if (Opts.Preserve.LexicalValues)
OS << "-preserveLexicalValues ";
if (Opts.Alignment != AlignKind::BitPacked) {
if (Opts.Alignment == AlignKind::BytePacked)
OS << "-bytePacked ";
else if (!Opts.Compression)
OS << "-preCompression ";
else
OS << "-compression ";
}
}
static constexpr auto kPreserveCDATA = PreserveCDATAKind::CDATA_NONE;
//static constexpr auto kPreserveCDATA = PreserveCDATAKind::CDATA_PRESERVE;
int ECDCTestRunner::runWithRet(StrRef ExiFile, StrRef XmlFile,
bool Diff, bool Dump, usize Skip) const {
using enum raw_ostream::Colors;
auto CoderLogLevel = exi::DebugFlag;
root::DumpOptions DO {
.Conforming = true,
.PreserveDeclaration = false,
.PreserveCDATA = kPreserveCDATA
};
#if EXI_LOGGING
ScopedSave LogLevelRestore(exi::DebugFlag, LogLevel::WARN);
#endif
auto CreateOutPath = [&, this] (SmallVecImpl<char>& Path) -> StrRef {
if (!ExiFile.empty()) {
sys::path::append(Path, ExamplePath, "out", ExiFile);
return StrRef(Path.begin(), Path.size());
}
sys::path::append(Path, ExamplePath, "out", sys::path::stem(XmlFile));
Path.append({'N','o','o','p','t'});
if (this->Opts.Alignment == AlignKind::BytePacked)
Path.push_back('B');
sys::path::replace_extension(Path, ".exi");
return StrRef(Path.begin(), Path.size());
};
SmallStr<80> FilenameStore;
StrRef OutExiFile = CreateOutPath(FilenameStore);
XMLDocument* Xml = nullptr;
MemoryBufferRef DecodeBuf;
SmallStr<0> EncodeBuf;
auto PrintHexDiff = [Skip] (StrRef Original, StrRef Encoded) {
PadByteDiffViewer(Original, Encoded, /*Width=*/16, /*Hex=*/true,
/*LabelX=*/true, /*SkipY=*/Skip);
};
auto PrintDiffOrCmp = [&, Diff] (StrRef Original, StrRef Encoded) {
if (Diff)
PrintHexDiff(Original, Encoded);
else
ByteCompareStrings(Original, Encoded);
};
Option<ExiDecoder> EDecoder;
Option<XMLDeserializer> ExiS;
ExiHeaderOnly HdrOnlyOpts {.HasOptions = false};
const bool& HasCookie = HdrOnlyOpts.HasCookie;
const bool& HasOptions = HdrOnlyOpts.HasOptions;
WithColor(errs(), BRIGHT_MAGENTA) << "BEGINNING RUN:\n";
if (!ExiFile.empty()) {
SmallStr<80> File;
sys::path::append(File, ExamplePath, ExiFile);
WithColor(errs(), BRIGHT_CYAN)
<< format("Decoding: \"{}\"", File.str()) << '\n';
XMLContainerRef Exi
= Mgr->getOptXMLRef(File.str(), errs())
.expect("could not locate file!");
auto MB = Exi.getBufferRef();
DecodeBuf = MB;
SetLogLevel(LogLevel::WARN);
ExiDecoder& Decoder = EDecoder.emplace(Opts);
XMLDeserializer& S = ExiS.emplace();
//S.PreserveCDATA = PreserveCDATAKind::CDATA_ESCAPE;
S.PreserveCDATA = PreserveCDATAKind::CDATA_NONE;
//S.SkipEmptyCH = true;
SetLogLevel(CoderLogLevel);
if (int Ret = Decode(Decoder, MB, &S)) {
WithColor(errs(), BRIGHT_RED)
<< "Decoding failed.\n";
return Ret;
}
SetLogLevel(LogLevel::WARN);
auto HOOptsOrErr = Decoder.headerOnly();
if (HOOptsOrErr.is_err()) {
WithColor(errs(), BRIGHT_RED)
<< "Decoding failed? "
<< HOOptsOrErr.error() << '\n';
return 1;
}
HdrOnlyOpts = *HOOptsOrErr;
WithColor(errs(), BRIGHT_GREEN)
<< "Decoding successful: "
<< exi_mangle_header(Decoder.header()) << "!\n\n";
}
/*Encoding*/ {
SmallStr<80> File;
sys::path::append(File, ExamplePath, XmlFile);
WithColor(errs(), BRIGHT_CYAN)
<< format("Encoding: \"{}\"", File.str()) << '\n';
Xml = &Mgr->getOptXMLDocument(File.str(), errs())
.expect("could not locate file!");
SetLogLevel(LogLevel::WARN);
Result EncoderOrErr = ExiEncoder::New(Opts);
if (!EncoderOrErr) {
errs() << EncoderOrErr.error() << '\n';
WithColor(errs(), BRIGHT_RED)
<< "Encoding failed.\n";
return 1;
}
ExiEncoder Encoder = std::move(*EncoderOrErr);
Encoder.setHeaderOnly(HdrOnlyOpts)
.expect("Options already compiled??");
//Encoder.hdrHasCookie(HasCookie)
// .expect("Options already compiled??");
//Encoder.hdrHasOptions(HasOptions)
// .expect("Options already compiled??");
XMLSerializer S(Xml);
S.PreserveCDATA = kPreserveCDATA;
//S.SkipEmptyCH = true;
SetLogLevel(CoderLogLevel);
LOG_INFO("Compiling header...");
SetLogLevel(LogLevel::INFO);
Result Factory = Encoder.setup();
if (!Factory) {
errs() << Factory.error() << '\n';
WithColor(errs(), BRIGHT_RED)
<< "Encoding failed.\n";
return 1;
}
SetLogLevel(CoderLogLevel);
LOG_INFO("Encoding body...");
if (auto E = Factory->encode(&S, EncodeBuf)) {
errs() << E << '\n';
WithColor(errs(), BRIGHT_RED)
<< "Encoding failed.\n";
return 1;
}
INFO_ONLY(dbgs() << '\n');
SetLogLevel(LogLevel::WARN);
WithColor(errs(), BRIGHT_GREEN)
<< "Encoding successful!\n\n";
if (!ExiFile.empty()) {
PrintDiffOrCmp(DecodeBuf.getBuffer(), EncodeBuf.str());
errs() << '\n';
}
}
/*Decoding, again*/ {
WithColor(errs(), BRIGHT_CYAN)
<< format("Decoding: \"{}\"", OutExiFile) << '\n';
auto MB = MemoryBuffer::getMemBuffer(EncodeBuf.n_str(), OutExiFile,
/*RequiresNullTerminator=*/false);
SetLogLevel(LogLevel::WARN);
ExiDecoder Decoder(Opts);
XMLDeserializer S;
S.PreserveCDATA = kPreserveCDATA;
S.SkipEmptyCH = true;
SetLogLevel(CoderLogLevel);
if (int Ret = Decode(Decoder, MB->getMemBufferRef(), &S)) {
WithColor(errs(), BRIGHT_RED)
<< "Decoding failed.\n";
return Ret;
}
SetLogLevel(LogLevel::WARN);
WithColor(errs(), BRIGHT_GREEN)
<< "Decoding (again) successful!\n\n";
if (Dump) {
auto CompareXml = [Xml] (XMLDocument* Other, SmallVecImpl<char>& V) {
if (!Xml)
return true;
raw_svector_ostream OS(V);
return compareXML(Xml, Other, OS);
};
auto Dump = [&DO] (XMLDocument& Doc) {
WithColor OS(errs(), BRIGHT_WHITE);
//XMLDump::full(Doc, DO);
XMLDump::raw(Doc, DO);
//XMLDump::info_tree(Doc, DO);
};
SmallStr<0> DErr, EErr;
bool DOk = !ExiS || CompareXml(&ExiS->document(), DErr);
bool EOk = CompareXml(&S.document(), EErr);
if (Xml) {
WithColor(errs(), MAGENTA) << "Original:\n";
Dump(*Xml);
}
if (ExiS && !DOk) {
WithColor OS(errs(), BRIGHT_RED);
OS << "Decoding result:\n" << DErr.str();
Dump(ExiS->document());
}
if (!EOk) {
WithColor OS(errs(), BRIGHT_RED);
OS << "Encoding result:\n" << EErr.str();
Dump(S.document());
}
} else if (Xml) {
using elem = StrRef;
using sequence = SmallVec<elem, 0>;
auto Dump = [P = Opts.Preserve] (XMLDocument& D, SmallVecImpl<char>& V) {
raw_svector_ostream OS(V);
OS.enable_colors(false);
XMLDump::full(D, XMLDumpOptions {
.OS = OS,
.InitialIndent = 0,
.Conforming = false,
.PrintRawNames = P.Prefixes,
.Preserve = P,
.PreserveDeclaration = false,
.PreserveCDATA = kPreserveCDATA
});
};
auto Diff = [] (sequence& LHS, sequence& RHS) {
dtl::Diff<elem> diff(LHS, RHS);
diff.onHuge();
diff.compose();
if (diff.getEditDistance() == 0)
return;
WithColor OS(errs(), raw_ostream::BRIGHT_WHITE);
diff.composeUnifiedHunks();
diff.printUnifiedFormat(OS);
};
SmallStr<0> Og, Enc, Dec;
Dump(*Xml, Og);
Dump(S.document(), Enc);
if (ExiS)
Dump(ExiS->document(), Dec);
sequence OgLines, EncLines, DecLines;
Og.str().split(OgLines, '\n', -1, false);
if (ExiS && Og.str() != Dec.str()) {
Dec.str().split(DecLines, '\n', -1, false);
WithColor(errs(), RED) << "Decoding result:\n";
Diff(OgLines, DecLines);
}
if (Og.str() != Enc.str()) {
Enc.str().split(EncLines, '\n', -1, false);
WithColor(errs(), RED) << "Encoding result:\n";
Diff(OgLines, EncLines);
}
}
}
if (auto E = WriteFile(OutExiFile, EncodeBuf)) {
logAllUnhandledErrors(std::move(E), errs());
return 1;
}
if (Cmds && EXIFICIENT_DIR) {
std::string Cmd;
Cmd.reserve(120);
raw_string_ostream OS(Cmd);
constexpr StrRef JarName = "exificient-jar-with-dependencies.jar";
OS << format("java -jar {}/{} -decode ", *EXIFICIENT_DIR, JarName.str());
// OS << "-retainEntityReference ";
if (HasCookie)
OS << "-includeCookie ";
if (HasOptions)
OS << "-includeOptions ";
AddExificientCmdOpts(OS, Opts);
sys::fs::make_absolute(FilenameStore);
OS << format("-i \"{0}\" -o \"{0}.xml\"", FilenameStore.str());
Cmds->RawCommands.emplace_back(std::move(Cmd));
//if (Opts.Preserve.Prefixes) {
Cmds->OldToNewMapping.emplace_back(
fmt::format("{}/{}", ExamplePath, XmlFile.str()),
fmt::format("{}.xml", FilenameStore.str()),
this->Opts.Preserve
);
//}
}
return 0;
}
void ECDCTestRunner::run(StrRef ExiFile, StrRef XmlFile,
bool Diff, bool Dump, usize Skip) const {
if (int Ret = runWithRet(ExiFile, XmlFile, Diff, Dump, Skip)) {
if (Cmds)
WriteExificientCmds(*Cmds);
std::exit(Ret);
}
}
#define MAKE_TEST_RUNNER(KIND, FOLDER, ...) \
[&Mgr, &ExificientFileData] () -> ECDCTestRunner { \
using enum exi::PreserveKind; \
const auto TheOpts = exi::make_preserve_opts(__VA_ARGS__); \
return ECDCTestRunner(Mgr, FOLDER, KIND, TheOpts, &ExificientFileData); \
}
/// Makes a test runner for "examples".
#define MAKE_EXTEST_RUNNER(KIND, ...) \
MAKE_TEST_RUNNER(KIND, "examples", ##__VA_ARGS__)
int main(int Argc, char* Argv[]) {
using enum raw_ostream::Colors;
SetLogLevel(LogLevel::WARN);
InitDriver X(Argc, Argv);
{
ExiOptions Opts;
if (!exi::exi_demangle_options(Opts, "iPcdlipV0"))
return 1;
errs() << exi::exi_mangle_options(Opts) << '\n';
Opts.SchemaID = std::make_unique<std::string>("BeerXML.xsd");
auto Mangled = exi::exi_mangle_options(Opts);
errs() << Mangled << '\n';
ExiOptions Opts2;
if (!exi::exi_demangle_options(Opts2, Mangled))
return 1;
exi_relassert(Opts2.SchemaID);
auto& SchemaID = *Opts2.SchemaID;
exi_relassert(SchemaID);
errs() << '\"' << *SchemaID << "\"\n";
//return 0;
}
{
SmallStr<32> EBuf, DBuf;
StrRef Original = "BeerXML.xsd";
StrRef Encoded = zbase32::encode(Original, EBuf);
Expected<StrRef> DecodedOrErr = zbase32::decode(Encoded, DBuf);
if (!DecodedOrErr) {
exi::String Err = toString(DecodedOrErr.takeError());
errs() << "Error decoding: " << Err << '\n';
return 1;
}
StrRef Decoded = *DecodedOrErr;
outs() << "Original: " << Original << '\n';
outs() << "Encoded: " << Encoded << '\n';
outs() << "Decoded: " << Decoded << '\n';
return Original != Decoded;
}
XMLManagerRef Mgr = make_refcounted<XMLManager>(ParseOpts);
#if STRESS_TEST_DECODING
if (int Ret = TestSchemalessDecoding(Mgr)) {
WithColor OS(outs(), BRIGHT_RED);
OS << "Decoding failed.\n";
return Ret;
}
WithColor OS(outs(), BRIGHT_GREEN);
OS << "Decoding successful!\n";
#else
// Add https://www.w3.org/TR/xmlschema-0/#ipo.xsd
CompareMetadata ExificientFileData;
if (auto Dir = sys::Process::GetEnv("EXIFICIENT_DIR")) {
SmallStr<80> FullPath;
sys::path::append(FullPath, *Dir, "exificient-jar-with-dependencies.jar");
if (sys::fs::exists(FullPath.str())) {
EXIFICIENT_DIR = std::move(Dir);
ExificientFileData.reserve(32);
}
// TODO: Add defaulted jar
}
/*BytePacked*/ {
auto Zil = MAKE_EXTEST_RUNNER(AlignKind::BytePacked);
auto Pfx = MAKE_EXTEST_RUNNER(AlignKind::BytePacked, Prefixes);
auto All = MAKE_EXTEST_RUNNER(AlignKind::BytePacked, All & ~LexicalValues);
Zil().run("SpecExampleB.exi", "SpecExample.xml");
Zil().run("BasicNooptB.exi", "Basic.xml");
Zil().run("ThaiNooptB.exi", "Thai.xml");
Zil().run("StackedPNNooptB.exi", "Stacked.xml");
Pfx().run("CustomersNooptB.exi", "Customers.xml");
Pfx().run("StackedPPNooptB.exi", "Stacked.xml");
All().run("NamespaceNooptB.exi", "Namespace.xml");
All().run("CDATANooptB.exi", "CDATA.xml", false, true);
All().run("el2-05.xml.exi", "el2-05.xml", false, true);
All().run("el2-05r.xml.exi", "el2-05r.xml");
All().run("el2-07.xml.exi", "el2-07.xml", false, true);
All().run("el2-09.xml.exi", "el2-09.xml");
All().run("el2-10.xml.exi", "el2-10.xml", false, true);
All().run("022NooptB.exi", "022.xml", false, true);
// TODO: Fix exificient replacing & with & and pruning CDATA
// Also fix outputs being in the wrong order...
All().run("044NooptB.exi", "044.xml", false, true);
//SetLogLevel(LogLevel::EXTRA);
All().run("044rNooptB.exi", "044r.xml", true);
// [Fatal Error] :1:57: White space is required between the '%' and the
// entity name in the parameter entity declaration.
// [ERROR] org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 57;
// White space is required between the '%' and the entity name in the parameter
// entity declaration.class javax.xml.transform.TransformerException
All().run("085NooptB.exi", "085.xml", true);
All().run("116NooptB.exi", "116.xml", false, true);
}
ExificientFileData.RawCommands.push_back("");
/*BitPacked*/ {
auto Zil = MAKE_EXTEST_RUNNER(AlignKind::BitPacked);
auto Pfx = MAKE_EXTEST_RUNNER(AlignKind::BitPacked, Prefixes);
auto All = MAKE_EXTEST_RUNNER(AlignKind::BitPacked, All & ~LexicalValues);
Zil().run("SpecExample.exi", "SpecExample.xml");
Zil().run("BasicNoopt.exi", "Basic.xml");
Zil().run("StackedPNNoopt.exi", "Stacked.xml");
Zil().run("ThaiNoopt.exi", "Thai.xml");
Pfx().run("CustomersNoopt.exi", "Customers.xml");
Pfx().run("StackedPPNoopt.exi", "Stacked.xml");
Pfx().run("OrdersSmall.exi", "OrdersSmall.xml");
All().run("NamespaceNoopt.exi", "Namespace.xml");
#if TEST_LARGE_EXAMPLES
SetLogLevel(LogLevel::WARN);
Pfx().run("Orders.exi", "Orders.xml", /*Diff=*/false);
#endif
}
return 0;
if (EXIFICIENT_DIR.has_value()) {
WriteExificientCmds(ExificientFileData);
errs() << "Running exificient...\n";
/// HACK: This isn't great, replace it with better impl.
#if EXI_ON_WIN32
std::system(".\\examples\\out\\ExificientCmds.bat "
"2> .\\examples\\out\\ExificientCmds.log");
#else
std::system("./examples/out/ExificientCmds.sh "
"2> ./examples/out/ExificientCmds.log");
#endif
WithColor(errs(), BRIGHT_GREEN)
<< "Wrote to 'examples/out/ExificientCmds.*'\n\n";
errs() << "Running comparisons...\n";
for (auto& [In, Out, P] : ExificientFileData.OldToNewMapping) {
errs() << " " << In << ": " << sys::path::filename(Out) << ' ';
auto& InDoc = Mgr->getOptXMLDocument(In, errs()).expect("???");
auto OutDoc = Mgr->getOptXMLDocument(Out, errs());
if (!OutDoc) {
WithColor(errs(), BRIGHT_YELLOW) << " [Failed to load]\n";
continue;
}
SmallStr<0> ErrMsg;
raw_svector_ostream OS(ErrMsg);
XMLCompareOptions Opts {
.OS = OS,
.Preserve = P,
.PreserveCDATA = XMLCompareOptions::CDATA_NONE,
.ExificientCompatibility = true
};
const bool IsEqual = exi::compareXML(&InDoc, &*OutDoc, Opts);
if (IsEqual)